0

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]]]
1
  • 2
    Are you asking how to remove duplicates? Commented Sep 12, 2022 at 15:32

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Won't work if only one item is in the list which will make it both the minimum and the maximum
I want to print A after removing the output.
@ThePyGuy The OP did not give any indication that there might be one-element lists. But, assuming there were, I would assume that such lists should be removed.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.