3

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.

4
  • 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. Commented Oct 4, 2014 at 4:15
  • oh yes... the set function... I am a bit unfamiliar with its use.. but I have indeed seen it in action. Commented Oct 4, 2014 at 5:44
  • 1
    It's not a function, but a full-blown data-type along with int, dict, list, and str. Commented Oct 4, 2014 at 5:49
  • oh wow... so its more than what I expected for it to be ! Thanks NickT for the great info ! Commented Oct 4, 2014 at 6:01

2 Answers 2

4

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'} 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks alot friend ! This helped alot.. and clear some ideas up. :)
4

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) 

1 Comment

Thank you Brother Hussain, that is a very nice example. The second example is short and concise, really good.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.