search

What is the use of the "contains" method in Python?

The **contains** method, also known as the **__contains__** method, is a special method in Python that allows objects to define their own behavior for the **in** operator. It is called when the expression **x in y** is evaluated, where **y** is an object and **x** is the value being searched for. If **y** has a **__contains__** method, it is called with **x** as an argument and the result of the method is used as the result of the **in** operator. The **contains** method should return a boolean value indicating whether **x** is contained in **y**.

For example, if you have a custom list object, you could define a **__contains__** method to make it possible to check if a value is in the list using the **in** operator. The following example demonstrates this:

class MyList:
    def __init__(self, values):
        self.values = values
    
    def __contains__(self, value):
        return value in self.values

my_list = MyList([1, 2, 3, 4, 5])
print(3 in my_list)  # True
print(6 in my_list)  # False

Related Questions You Might Be Interested