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

Question:

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]]]
Asked By: user19977266

||

Answers:

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.

Answered By: Tim Biegeleisen

You can count number of equal items in list with list.count method.
Considering that all elements of the A cannot be empty you can filter them like this.

filtered = [el for el in A if el.count(el[0]) != len(el)]

Or to be sure that code will not throw the IndexError on empty items, you can check the length of an item.

filtered = [el for el in A if len(el) and el.count(el[0]) != len(el)]

This approach will also works for strings and other types.

Answered By: Danil Martyniuk
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.