Implement Stateful Iterators
Core idea
A custom iterator stores its progress, returns itself from __iter__, and advances in __next__. When no items remain, raise StopIteration and remain exhausted on subsequent calls. A reusable container should instead create a fresh iterator each time.
class Countdown: def __init__(self, n): self.n = n def __iter__(self): return self def __next__(self): if self.n <= 0: raise StopIteration value = self.n self.n -= 1 return valueprint(list(Countdown(3)))State decreases once per returned item.
Check exhaustion twice
class Empty: def __iter__(self): return self def __next__(self): raise StopIterationit = Empty()print(next(it, "end"), next(it, "end"))An exhausted iterator must keep signalling exhaustion.
Intentional failure: wrong iterator return
class Bad: def __iter__(self): return [1, 2]iter(Bad())iter must return an iterator, not merely an iterable.
Common mistake
Do not return None to signal completion; it is a valid item. Do not reset progress inside iter of an iterator.
Practice
Implement a bounded increasing counter, then test two separate instances and repeated next calls after exhaustion.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Custom iterators
Check your understanding of custom iterators.
What is printed?
class Once: def __init__(self): self.done = False def __iter__(self): return self def __next__(self): if self.done: raise StopIteration self.done = True return 3print(list(Once()))What happens?
class Bad: def __iter__(self): return []iter(Bad())What is printed?
class Source: def __iter__(self): return iter([None])print(list(Source()))What must a compliant exhausted iterator do?