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?
Python string __contains__() is an instance method and returns boolean value True or False depending on whether the string object contains the specified string object or not. Note that the Python string contains() method is case sensitive.
To check if the list contains an element in Python, use the “in” operator. The “in” operator checks if the list contains a specific item or not. It can also check if the element exists on the list or not using the list.
__class__ is an attribute on the object that refers to the class from which the object was created. a. __class__ # Output: <class 'int'> b. __class__ # Output: <class 'float'> After simple data types, let's now understand the type function and __class__ attribute with the help of a user-defined class, Human .
In Python, you'll be able to use a list function that creates a group that will be manipulated for your analysis. This collection of data is named a list object. While all methods are functions in Python, not all functions are methods. There's a key difference between functions and methods in Python.
>>> 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 roughly equivalent to:
def __contains__(self, other):
return any(other is item or other == item for item in self)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With