Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Removing a list containing the same elements from a list in Python

Is there a straightforward way to remove a list containing all elements the same instead of specifying the actual location? For example, A[1] has to be removed because all the elements are the same?

A=[[[1],[2],[2]],[[3],[3],[3]],[[4],[5],[4]]]
print(A)

A.remove(A[1])
print(A)

The output is and should be

[[[1],[2],[2]],[[4],[5],[4]]]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

We can use a list comprehension here:

A = [[[1],[2],[2]],[[3],[3],[3]],[[4],[5],[4]]]
output = [x for x in A if min(x) != max(x)]
print(output)  # [[[1], [2], [2]], [[4], [5], [4]]]

We can identify a sublist as candidate for being removed by checking if the min and max values be the same. If those two values are not the same, then we retain the sublist.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading