pythonlistclassfunctioncontains

Python List Class __contains__ Method Functionality


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?


Solution

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