__iter__ — Easy Examples
Returns an iterator; makes the object usable in for loops
Implementing __iter__
Basic implementation of __iter__ in a class.
python
class Countdown: def __init__(self, start): self.start = start def __iter__(self): n = self.start while n > 0: yield n n -= 1 for num in Countdown(5): print(num)
__iter__ returns an iterator; makes the object usable in for loops. Implementing it lets you customize how Python interacts with your objects.
__iter__ in action
Seeing __iter__ called by Python's built-in operations.
python
# How Python calls __iter__ automatically class Demo: def __init__(self, value): self.value = value def __iter__(self): print(f"__iter__ was called!") return self d = Demo(42) # This triggers __iter__: for x in d: break
Python automatically calls __iter__ when you use the corresponding operator or function on your object.
Want to try these examples interactively?
Open Easy Playground