Python List Class __contains__ Method Functionalit

2019-04-06 01:46发布

问题:

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?

回答1:

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



回答2:

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.