How to find values โ€‹โ€‹of duplicates in a Python list

I was wondering how to find out when the user enters a value, that value already exists in the list.

For example:

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

      

user inputs:

'boo'

      

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

+3


source to share


2 answers


Use the 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 the order of the 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'}

      

+4


source


Another way you can do is using 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 is ineffective. So to make it efficient the usage is set as falsetru points in the answer: -

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

      

+4


source







All Articles