Python List Class __contains__ Method Functionalit

2019-04-06 01:37发布

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?

2条回答
祖国的老花朵
2楼-- · 2019-04-06 02:27

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.

查看更多
劫难
3楼-- · 2019-04-06 02:30
>>> 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.

查看更多
登录 后发表回答