Reputation:
I have a list say p = [1,2,3,4,2]
Is there any way of returning bool value True
if it contains a duplicate using only find, indexing, slicing, len() etc methods and not dict, tuple etc.
I used this code:
for e in p:
duplicate = p.find(e, e+1)
if duplicate in p:
return True
Upvotes: 1
Views: 664
Reputation: 500883
Here is the easy way:
return len(p) != len(set(p))
A less efficient way that doesn't use set
:
for i in range(len(p)):
if p[i] in p[i+1:]:
return True
return False
This second approach is not very idiomatic, but avoids all but the most basic features of the language (including tuples).
Here is one more way:
while p:
e = p.pop()
if e in p:
return True
return False
This is simple, but does modify the list.
One final way I am going to demonstrate is:
s = sorted(p)
for i in range(1, len(s)):
if s[i] == s[i - 1]:
return True
return False
This works by sorting p
and then comparing every pair of consecutive elements.
Upvotes: 6
Reputation: 3704
Using collections.Counter
>>> import collections
>>> p
[1, 2, 3, 4, 2]
>>> if collections.Counter(p).most_common()[0][1] > 1:
... print('duplicate found')
...
duplicate found
>>> if collections.Counter(set(p)).most_common()[0][1] > 1:
... print('duplicate found')
...
>>>
Upvotes: 1
Reputation: 86260
Here's a very simple way to do it. It may be slow for very large lists.
def has_duplicates(lst):
for e in lst:
lst = lst[1:]
if e in lst: return True
return False
Upvotes: 0
Reputation: 390
>>> p = [1, 2, 3, 4, 2]
>>> len(set(p)) == len(p)
False
You can find more information about sets in the Python Documentation.
Upvotes: 2
Reputation: 27832
You could also use list.count
:
def has_duplicates(p):
for e in p:
if p.count(e) > 1:
return True
return False
Upvotes: 5
Reputation: 78630
If you have to do it this way, you could do:
def has_duplicates(lst):
for i, e in enumerate(lst[::-1]):
if lst.index(e) != len(lst) - i - 1:
return True
return False
This iterates through the list in reverse order (since index
searches from the start of the list). But it's better simply to do:
def has_duplicates(lst):
return len(set(lst)) != len(lst)
Upvotes: 1