Is there a short contains function for lists?

Joan Venge picture Joan Venge · Oct 17, 2012 · Viewed 651.5k times · Source

I see people are using any to gather another list to see if an item exists in a list, but is there a quick way to just do?:

if list.contains(myItem):
    # do something

Answer

defuz picture defuz · Oct 17, 2012

You can use this syntax:

if myItem in list:
    # do something

Also, inverse operator:

if myItem not in list:
    # do something

It's work fine for lists, tuples, sets and dicts (check keys).

Note that this is an O(n) operation in lists and tuples, but an O(1) operation in sets and dicts.