__contains__ — Easy Examples
Called by the 'in' operator to test membership
Implementing __contains__
Basic implementation of __contains__ in a class.
python
class NumberRange: def __init__(self, start, end): self.start = start self.end = end def __contains__(self, item): return self.start <= item <= self.end r = NumberRange(1, 10) print(5 in r) print(15 in r)
__contains__ called by the 'in' operator to test membership. Implementing it lets you customize how Python interacts with your objects.
__contains__ in action
Seeing __contains__ called by Python's built-in operations.
python
# How Python calls __contains__ automatically class Demo: def __init__(self, value): self.value = value def __contains__(self, other): print(f"__contains__ was called!") return self d = Demo(42) # This triggers __contains__: print(1 in d)
Python automatically calls __contains__ when you use the corresponding operator or function on your object.
Want to try these examples interactively?
Open Easy Playground