object .__ contains__ in Python

Python Methods and Functions

Allows you to define a mechanism for checking if an element is in a container object.

object .__ contains __ (self, item)

-> bool

self - Reference to the object.

item - The element, the presence of which in the object must be determined. 

Called when checking for the presence of an element in the container object using the in .

Should return True if the specified element is contained in the object, otherwise False .

  class MyContainer: 

def __init __ (self):
self.items = [1, 2]

def __contains __ (self, ite m) :
return item in self.items

my_container = MyContainer ()

1 in my_container # True
2 in my_container # True
3 in my_container # False


For mappings you should search for an element among the keys, not among the values.

For objects in which this method is not defined, the presence of the element will be found out: