Reputation: 2046
If there's a list the elements of which are [2,2,3,2,2]
. I want to find the element that is unique, which is 3
this time.
I think I could do this with count()
method and a few loops, but I wonder if there are simpler and efficient ways to do this.
Upvotes: 1
Views: 62
Reputation: 8398
You can use Counter and then min,
In [4]: from collections import Counter
In [5]: x = [2,2,3,2,2]
In [6]: c = Counter(x)
In [7]: min(c, key=c.get)
Out[7]: 3
In [8]:
Upvotes: -1
Reputation: 26037
Without any modules, you can simply perform xor
of all elements to get the unique item.
This outputs 0
, if there is no unique item as noted by @KeyurPotdar.
l = [2,2,3,2,2]
out = l[0]
for elem in l[1:]:
out = out ^ elem
print(out)
# 3
Upvotes: 0
Reputation: 20434
You can use collections.Counter:
>>> import collections
>>> l = [2,2,3,2,2]
>>> next(k for k, v in collections.Counter(l).items() if v == 1)
3
Upvotes: 6