Andre
Andre

Reputation: 1661

How to find duplicates values in list Python

I was wondering how can I know if when a user inputs a value, that value already exists in a list.

For example;

lis = ['foo', 'boo', 'hoo']

user inputs:

'boo'

Now my question is how can I tell the user this value already exists inside the list.

Upvotes: 3

Views: 8414

Answers (2)

Hussain Shabbir
Hussain Shabbir

Reputation: 15015

One more way you can do is use collections :-

import collections
lis = ['foo', 'boo', 'hoo']
# Now if user inputs boo
lis.append('boo')
print [x for x, y in collections.Counter(lis).items() if y > 1]
# Now it will print the duplicate value in output:-
boo

But the above one is not efficient. So for make it efficient use set as falsetru indicates in the answer:-

totalList= set()
uniq = []
for x in lis:
    if x not in totalList:
        uniq.append(x)
        totalList.add(x)

Upvotes: 4

falsetru
falsetru

Reputation: 369064

Use in operator:

>>> lis = ['foo', 'boo', 'hoo']
>>> 'boo' in lis
True
>>> 'zoo' in lis
False

You can also use lis.index which will return the index of the element.

>>> lis.index('boo')
1

If the element is not found, it will raise ValueError:

>>> lis.index('zoo')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: 'zoo' is not in list

UPDATE

As Nick T commented, if you don't care about order of items, you can use set:

>>> lis = {'foo', 'boo', 'hoo'}  # set literal  == set(['foo', 'boo', 'hoo'])
>>> lis.add('foo')  # duplicated item is not added.
>>> lis
{'boo', 'hoo', 'foo'}

Upvotes: 4

Related Questions