3

I have a list as below

[('generators', 'generator'), ('game', 'games'), ('generator', 'generators'), ('games', 'game'), ('challenge', 'challenges'), ('challenges', 'challenge')]

Pairs ('game', 'games') and ('games', 'game') are kind of same but they are in different order.

The output I am trying to achieve

[('generators', 'generator'), ('games', 'game'), ('challenge', 'challenges')]

How can I remove pairs as such from above list ?

Any suggestions, greatly appreciated.

Raja G
  • 5,973
  • 14
  • 49
  • 82

2 Answers2

4

You can use an unordered hashable data structure within a set. frozenset() is your friend here:

In [7]: {frozenset(i) for i in your_list}
Out[7]: 
{frozenset({'generator', 'generators'}),
 frozenset({'game', 'games'}),
 frozenset({'challenge', 'challenges'})}

Note that in order to avoid looping over your list it's better to do this at the first place while creating your list.

Mazdak
  • 105,000
  • 18
  • 159
  • 188
  • this answer is good, but would be better migrated in the duplicate link (where there's already a good, different answer) – Jean-François Fabre Oct 07 '18 at 08:20
  • @Jean-FrançoisFabre I think in such cases it's better to mark the other one as duplicated. That answer is terrible tho. At least for cases were items in tuples (sub-sets) are not equal. – Mazdak Oct 07 '18 at 08:21
  • @Kasrâmvd would you apply this process if the object type needed to be maintained? So if you needed `list(set(tuple(sorted(i)) for i in your_list))`? – Josmoor98 Mar 01 '19 at 14:08
  • What do you mean by ` the object type needed to be maintained`? We don't do anything to object type. Also, your code is completely different than this answer. – Mazdak Mar 01 '19 at 15:30
1

You could sort the list and then take every other index using list comprehension

lista = [i for i in sorted(tups)[::2]]
# [('challenge', 'challenges'), ('game', 'games'), ('generator', 'generators')]
vash_the_stampede
  • 4,590
  • 1
  • 8
  • 20