appleLover
appleLover

Reputation: 15701

Get Unique Tuples from List , Python

>>> a= ('one', 'a')
>>> b = ('two', 'b')
>>> c = ('three', 'a')
>>> l = [a, b, c]
>>> l
[('one', 'a'), ('two', 'b'), ('three', 'a')]

How can I check for only the elements of this list with a unique second entry (column? item?), and then grab the first entry found on the list. Desired output is

>>> l
[('one', 'a'), ('two', 'b')]

Upvotes: 11

Views: 11630

Answers (2)

Blender
Blender

Reputation: 298532

If order isn't important, you can use a dictionary:

d = {}

for t in reversed(l):
    d[t[1]] = t

print d.values()

Or more concisely:

{t[1]: t for t in reversed(l)}.values()

If you don't reverse the list, ('three', 'a') will overwrite ('one', 'a').

Upvotes: 2

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251166

Use a set (if the second item is hash-able):

>>> lis = [('one', 'a'), ('two', 'b'), ('three', 'a')]
>>> seen = set()
>>> [item for item in lis if item[1] not in seen and not seen.add(item[1])]
[('one', 'a'), ('two', 'b')]

The above code is equivalent to:

>>> seen = set()
>>> ans = []
for item in lis:
    if item[1] not in seen:
        ans.append(item)
        seen.add(item[1])
...         
>>> ans
[('one', 'a'), ('two', 'b')]

Upvotes: 16

Related Questions