How to find duplicates values in list Python -
How to find duplicates values in list Python -
i wondering how can know if when user inputs value, value exists in list.
for example;
lis = ['foo', 'boo', 'hoo']
user inputs:
'boo'
now question how can tell user value exists within list.
use in
operator:
>>> lis = ['foo', 'boo', 'hoo'] >>> 'boo' in lis true >>> 'zoo' in lis false
you can utilize lis.index
homecoming index of element.
>>> lis.index('boo') 1
if element not found, raise valueerror
:
>>> lis.index('zoo') traceback (most recent phone call last): file "<stdin>", line 1, in <module> valueerror: 'zoo' not in list
update
as nick t commented, if don't care order of items, can utilize set
:
>>> lis = {'foo', 'boo', 'hoo'} # set literal == set(['foo', 'boo', 'hoo']) >>> lis.add('foo') # duplicated item not added. >>> lis {'boo', 'hoo', 'foo'}
python list duplicates
Comments
Post a Comment