Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 510
Jim West Avatar asked Apr 18 '12 13:04

Jim West


People also ask

What does __ contains __ do in Python?

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.

Does Python list have Contains method?

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.

What is __ class __ in Python?

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

Is a list method a function in Python?

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.


2 Answers

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

like image 76
Silas Ray Avatar answered Oct 04 '22 03:10

Silas Ray


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)
  
like image 31
Mark Bell Avatar answered Oct 04 '22 03:10

Mark Bell