Member-only story

The Hidden Power of Stateful Iterators in Python

Take control of iteration with objects that remember their state

Max N
2 min readApr 24, 2024

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.

Preserving Iteration State

--

--

Max N
Max N

Written by Max N

A writer that writes about JavaScript and Python to beginners. If you find my articles helpful, feel free to follow.

No responses yet