Checking if all elements in a list are unique Checking if all elements in a list are unique python python

Checking if all elements in a list are unique


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.


Here is a two-liner that will also do early exit:

>>> def allUnique(x):...     seen = set()...     return not any(i in seen or seen.add(i) for i in x)...>>> allUnique("ABCDEF")True>>> allUnique("ABACDEF")False

If the elements of x aren't hashable, then you'll have to resort to using a list for seen:

>>> def allUnique(x):...     seen = list()...     return not any(i in seen or seen.append(i) for i in x)...>>> allUnique([list("ABC"), list("DEF")])True>>> allUnique([list("ABC"), list("DEF"), list("ABC")])False


An early-exit solution could be

def unique_values(g):    s = set()    for x in g:        if x in s: return False        s.add(x)    return True

however for small cases or if early-exiting is not the common case then I would expect len(x) != len(set(x)) being the fastest method.