0

If I have a list such as

[[a,b], [b,a], [c,d], [d,c]]

But with letter pair lists not adjacent, how do I iterate through the list and end up with only one of the letter pairs?

aviya.developer
  • 3,343
  • 2
  • 15
  • 41
cgrifel
  • 1
  • 1

1 Answers1

1

If you don't care about order then the easiest way is to use sets and frozensets:

lst = [[a,b], [b,a], [c,d], [d,c]] 
result =  [list(x) for x in {frozenset(t) for t in lst}]

# result output: [[a,b], [c,d]]

Since frozenset([a,b]) == frozenset([b,a]), the set comprehension {frozenset(t) for t in lst} will include each pair only once. The outer list comprehension converts back the set of frozensets to a list of lists.

aviya.developer
  • 3,343
  • 2
  • 15
  • 41
Błotosmętek
  • 12,717
  • 19
  • 29