0

I don't mean situation like this:

my_list = [("a", "b"), ("c", "d"), ("d", "f"), ("a", "b"), ("b", "c")]

and eliminating the second tuple ("a", "b"), but rather something like:

my_list = [("a", "b"), ("c", "c"), ("d", "f"), ("a", "b"), ("b", "b")]

and removing tuples ("c", "c") and ("b", "b").

In the example above, the following one-liner does the job:

my_list_cleared = [n for n in my_list if n[0] != n[1]]

But is there also a one-liner if there are three and more elements in tuples (like: ("a", "a", "b", "c"))?

AbreQueVoy
  • 1,748
  • 8
  • 31
  • 52
  • Check out [`collections.Counter`](https://docs.python.org/3/library/collections.html#collections.Counter) – wim Oct 15 '20 at 15:19
  • In the greater than 2 case, do you want to remove if all elements in the tuple are the same, or any 2 are repeating? – Tomerikoo Oct 15 '20 at 15:22
  • @Tomerikoo: all values should be unique. – AbreQueVoy Oct 15 '20 at 15:23
  • 2
    Does this answer your question? [Checking if all elements in a list are unique](https://stackoverflow.com/questions/5278122/checking-if-all-elements-in-a-list-are-unique) where in your case the check is for each tuple and not the list as a whole – Tomerikoo Oct 15 '20 at 15:24
  • Yes, this too; it's a generic implementation of Cory Kramer's response. Thank you for your efforts. – AbreQueVoy Oct 15 '20 at 15:27
  • 1
    [testing whether a tuple has all distinct elements](https://stackoverflow.com/questions/22891726/testing-whether-a-tuple-has-all-distinct-elements) – Tomerikoo Oct 15 '20 at 15:29

1 Answers1

1

You can create a set of each tuple, which will remove duplicates. If that set is the same length as the original tuple, there were no duplicates, so keep that element. This can be done in a list comprehension and will work with tuples of arbitrary length.

>>> [i for i in my_list if len(set(i)) == len(i)]
[('a', 'b'), ('d', 'f'), ('a', 'b')]
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218