Home > Net >  Removing a list containing the same elements from a list in Python
Removing a list containing the same elements from a list in Python

Time:09-13

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]]]

CodePudding user response:

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.

CodePudding user response:

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.

  • Related