__contains__
- Python course
- Intermediate
- Lesson 34/116
- 4 min
Learn the in operator with __contains__.
The __contains__ method
__contains__(self, item) defines the in operator. Writing item in obj calls __contains__; the result is True or False.
Example: class Box:\n def __contains__(self, item):\n return item in self.items. Writing 2 in b returns whether 2 is in b.items. This makes membership checks natural for collection classes.
Membership check
If __contains__ is not defined, Python falls back to __iter__ or __getitem__ for membership checks; but __contains__ is faster and more direct.
Example: in the Box class, writing 2 in b calls __contains__. This method searches the inner list and returns True/False. not in also works automatically; no separate method is needed.
Practice Add __contains__ to Box
Define the Box class. Add def __init__(self, items): with self.items = items in the body. Add def __contains__(self, item):; in the body write return item in self.items. Then call b = Box([1, 2, 3]) and print(2 in b).
Starter code
# Define the Box classSample solution
# Define the Box class
class Box:
def __init__(self, items):
self.items = items
def __contains__(self, item):
return item in self.items
b = Box([1, 2, 3])
print(2 in b)Expected output
True
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the __contains__ concepts
| Term | Meaning |
|---|---|
__contains__ |
in operator |
item in self.items |
Inner check |
True/False |
Return value |
2 Which method does x in obj call?
- __contains__ Correct answer
- __iter__
- __getitem__
- __in__
Explanation: The in operator calls the __contains__ method.
3 Complete the __contains__ signature
class Box:
def __contains__(self, ____):
return item in self.items
class Box:
def __contains__(self, item):
return item in self.items
Explanation: __contains__ takes self and item parameters.