I want to build a function that will return True if any two items in a list are the same.
For example, [1,7,3,7,4]
should return True
and ["one","ONE","One"]
should return False
.
I need help with which parts of python look for duplicates.
I want to build a function that will return True if any two items in a list are the same.
For example, [1,7,3,7,4]
should return True
and ["one","ONE","One"]
should return False
.
I need help with which parts of python look for duplicates.
Loop over the values and use a set
to track what you have already seen. As soon as you see a value again, return True
:
def has_duplicates(lst):
seen = set()
for elem in lst:
if elem in seen:
return True
seen.add(elem)
return False
This is very efficient in that it short-circuits; it won't loop over the whole list if a duplicate has been detected early on.
Martijn's answer is the best, but with a few exceptions, this is worth a try.
>>> chk = lambda x: len(l) != len(set(l)) # check the length after removing dupes.
>>> l = [1,7,3,7,4]
>>> chk(l)
True
>>> l = ["one","ONE","One"]
>>> chk(l)
False
Note - As Martijn mentions in a comment, this is a slower process.
Using a collections.Counter dict:
from collections import Counter
def has_dupes(l):
# if most repeated key count is > 1 we have at least one dupe
return Counter(l).most_common(1)[0][1] > 1
Or use any
:
def has_dupes(l):
return any(v > 1 for v in Counter(l).values())