Does the __contains__
method of a list class check whether an object itself is an element of a list, or does it check whether the list contains an element equivalent to the given parameter?
Could you give me an example to demonstrate?
Does the __contains__
method of a list class check whether an object itself is an element of a list, or does it check whether the list contains an element equivalent to the given parameter?
Could you give me an example to demonstrate?
>>> 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 equivalent to:
def __contains__(self, other):
return any(other is item or other == item for item in self)
x in y
is equivalent to any(x is e or x == e for e in y)
." –
Longerich It depends on the class how it does the check. For the builtin list
it uses the ==
operator; otherwise you couldn't e.g. use 'something' in somelist
safely.
To be more specific, it check if the item is equal to an item in the list - so internally it's most likely a hash(a) == hash(b)
comparison; if the hashes are equal the objects itself are probably compared, too.
__eq__
method which has been (involuntarily) picked up by __contains__
or in
. Therefore, it's most likely list
implements a a.__eq__(b)
comparison. –
Winshell It checks the value
>>> x = 8888
>>> y = 8888
>>> list1 = [x]
>>> print(id(x))
140452322647920
>>> print(id(y))
140452322648016
>>> y in list1
True
© 2022 - 2024 — McMap. All rights reserved.