Sobes.tech
Junior — Middle

What is the role of the __contains__ method in implementing an iterator in Python?

sobes.tech AI

Answer from AI

The __contains__ method in Python is responsible for checking whether an element belongs to a collection and is used with the in operator. In the context of an iterator or collection, if you implement __contains__, you can define exactly how the check for an element's presence is performed.

For example, if you have a class that implements an iterator, and you want to support the check if item in obj:, you need to implement the __contains__ method.

Example:

class MyCollection:
    def __init__(self, items):
        self.items = items

    def __iter__(self):
        return iter(self.items)

    def __contains__(self, item):
        for elem in self.items:
            if elem == item:
                return True
        return False

col = MyCollection([1, 2, 3])
print(2 in col)  # True
print(5 in col)  # False

Thus, __contains__ allows for an efficient implementation of membership testing, which is important for the convenience of using custom collections and iterators.