user225312 user225312 - 1 year ago 67
Python Question

Checking if all elements in a list are unique

What is the best way (best as in the conventional way) of checking whether all elements in a list are unique?

My current approach using a


>>> x = [1, 1, 1, 2, 3, 4, 5, 6, 2]
>>> counter = Counter(x)
>>> for values in counter.itervalues():
if values > 1:
# do something

Can I do better?

yan yan
Answer Source

Not the most efficient, but straight forward and concise:

if len(x) > len(set(x)):
   pass # do something

Probably won't make much of a difference for short lists.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download