Is there a short contains function for lists? Is there a short contains function for lists? python python

Is there a short contains function for lists?

You can use this syntax:

if myItem in list:    # do something

Also, inverse operator:

if myItem not in list:    # do something

It works 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.

In addition to what other have said, you may also be interested to know that what in does is to call the list.__contains__ method, that you can define on any class you write and can get extremely handy to use python at his full extent.  

A dumb use may be:

>>> class ContainsEverything:    def __init__(self):        return None    def __contains__(self, *elem, **k):        return True>>> a = ContainsEverything()>>> 3 in aTrue>>> a in aTrue>>> False in aTrue>>> False not in aFalse>>>         

I came up with this one liner recently for getting True if a list contains any number of occurrences of an item, or False if it contains no occurrences or nothing at all. Using next(...) gives this a default return value (False) and means it should run significantly faster than running the whole list comprehension.

list_does_contain = next((True for item in list_to_test if item == test_item), False)