Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.

share|improve this question
1  
Your question is more avoiding duplicates in a list. If you don't care about order, you could also use a set, which, if you attempt to add a duplicate, it ignores it. –  Nick T 5 hours ago
    
oh yes... the set function... I am a bit unfamiliar with its use.. but I have indeed seen it in action. –  Ali 4 hours ago
1  
It's not a function, but a full-blown data-type along with int, dict, list, and str. –  Nick T 3 hours ago
    
oh wow... so its more than what I expected for it to be ! Thanks NickT for the great info ! –  Ali 3 hours ago

1 Answer 1

up vote 1 down vote accepted

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'}
share|improve this answer
    
Thanks alot friend ! This helped alot.. and clear some ideas up. :) –  Ali 4 hours ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.