Python List Class __contains__ Method Functionality
It checks the value
>>> x = 8888
>>> y = 8888
>>> list1 = [x]
>>> print(id(x))
140452322647920
>>> print(id(y))
140452322648016
>>> y in list1
True
>>> a = [[]]
>>> b = []
>>> b in a
True
>>> b is a[0]
False
This proves that it is a value check (by default at least), not an identity check. Keep in mind though that a class can if desired override __contains__()
to make it an identity check. But again, by default, no.
Python lists (and tuples) first check whether an object itself is an element of a list (using the is
operator) and only if that is False then does it check whether the object is equal to an item in the list (using the ==
operator). You can see this by creating an object that is not equal to itself:
>>> class X:
... def __eq__(self, other):
... return False
...
>>> x = X()
>>> x == x
False
However since x is x
, __contains__
still recognises that this object is in a list
>>> x in [1, 'a', x, 7]
True
That is, a lists __contains__
method is roughly equivalent to:
def __contains__(self, other):
return any(other is item or other == item for item in self)