maynull
maynull

Reputation: 2046

How can I get the value that is unique in a list?

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

Answers (3)

Nishant Nawarkhede
Nishant Nawarkhede

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

Austin
Austin

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

Joe Iddon
Joe Iddon

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

Related Questions