in — Advanced Examples
Membership test operator; also used in for loops to iterate over items
Custom __contains__
Making your own objects support 'in'.
python
class DateRange: def __init__(self, start, end): self.start = start self.end = end def __contains__(self, date): return self.start <= date <= self.end def __repr__(self): return f"DateRange({self.start}, {self.end})" from datetime import date q1 = DateRange(date(2024, 1, 1), date(2024, 3, 31)) print(f"Feb 15 in Q1: {date(2024, 2, 15) in q1}") print(f"Apr 15 in Q1: {date(2024, 4, 15) in q1}") # Without __contains__, Python falls back to __iter__ class Odds: def __iter__(self): n = 1 while n < 20: yield n n += 2 odds = Odds() print(f"7 in odds: {7 in odds}") print(f"8 in odds: {8 in odds}")
Expected Output
Feb 15 in Q1: True Apr 15 in Q1: False 7 in odds: True 8 in odds: False
Implement __contains__ for O(1) membership testing. Without it, Python falls back to iterating through __iter__, which is O(n).
Want to try these examples interactively?
Open Advanced Playground