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?
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.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.