Member-only story
Most basic iterators in Python are stateless — they simply return values from a sequence without remembering anything. But by creating a custom iterator class, you can define stateful iterators that keep track of iteration state internally. This unlocks new capabilities for complex iteration patterns.
Defining Iterator Classes
To create a stateful iterator, define a class with iter() and next() methods. The iter() method should return self, and next() should handle retrieving and updating the state.
class CountUp:
def __init__(self, start=0, step=1):
self.current = start
self.step = step
def __iter__(self):
return self
def __next__(self):
result = self.current
self.current += self.step
return result
counter = CountUp(3, 2)
print(next(counter)) # 3
print(next(counter)) # 5
print(next(counter)) # 7
This CountUp iterator tracks its current value as internal state, updating it each time next() is called.