Check if item is in an array / list

SomeKittens picture SomeKittens · Jun 28, 2012 · Viewed 489k times · Source

If I've got an array of strings, can I check to see if a string is in the array without doing a for loop? Specifically, I'm looking for a way to do it within an if statement, so something like this:

if [check that item is in array]:

Answer

Sven Marnach picture Sven Marnach · Jun 28, 2012

Assuming you mean "list" where you say "array", you can do

if item in my_list:
    # whatever

This works for any collection, not just for lists. For dictionaries, it checks whether the given key is present in the dictionary.