Lesson · Iteration Protocol
Custom Iterators
55 min readCustom Iterators
A custom iterator stores iteration state and implements `__iter__` and `__next__`. Writing one makes the iterator protocol concrete and shows why reusable containers are usually separate from their iterators.
Learning goals
- Explain the two obligations a class takes on when it implements
__iter__and__next__. - Trace
Countdown(3)throughlist()and say which method runs at each step. - Predict what a second pass over a self-iterator yields, and adjust the class so it can be restarted.
- Raise
StopIterationat the right moment so loops end cleanly instead of spinning or stopping early. - Design a container whose
__iter__returns a fresh iterator rather thanself.
Mental model
A custom iterator is a class on the right side of that flow: it stores the position in an attribute, returns one value per __next__ call, and signals the end with StopIteration. If __iter__ returns self, the object is a self-iterator and only one pass ever exists; returning a freshly created iterator is what makes a container reusable.
iter() builds an object that holds the position
StopIteration is how every consumer learns the end
Mental model
the same mechanism as a compact list
iter(obj) ──▶ obj.__iter__() ──▶ iterator (holds state)
│
next()│advances state once
▼
value, or StopIteration at the endCore idea
Writing __iter__ and __next__ turns the protocol from a rule you observe into a class you control: __next__ reads the state, produces one value, and advances the state before returning. The most consequential design choice is what __iter__ returns: self makes the object a one-pass iterator, while a new iterator per call keeps the container reusable. StopIteration is not an error path; it is how __next__ reports that the state has run out.
__iter__
__iter__ is the method iter() calls to obtain an iterator from an object, and it must return an iterator. An iterator's own __iter__ returns self, which is what lets it act as both the iterable and the thing that advances.
__next__
__next__ is the method next() calls to produce the next value: it returns one item per call and raises StopIteration when no items remain. A for loop calls it repeatedly and treats StopIteration as the normal end of the loop.
Iterator state
An iterator stores whatever state is necessary to know the next value. Each next() call advances that state exactly once.
StopIteration
An iterator signals normal exhaustion by raising StopIteration. A for loop catches this internally and stops without exposing it as an error.
Self-iterators
A self-iterator returns self from __iter__ and therefore represents one advancing iteration state. This design is appropriate for iterator objects but not usually for reusable containers.
Reusable collection objects
A reusable collection's __iter__ should usually return a new iterator object each time. Returning self is appropriate only when the collection object itself represents one advancing iteration.
Walkthrough
Countdown(3)stores the position inself.current = 3, so the object itself is the iteration state.list(...)callsiter()first, which reaches__iter__and receivesself, then callsnext()repeatedly, so each__next__call consumes one value fromself.current.- The calls return
3,2, and1; on the fourth callself.current <= 0is true,StopIterationis raised, andlisttreats that as the end, so it returns[3, 2, 1]. - Predict before running: the first value returned, the value of
self.currentafter the pass, and what a secondlistcall on the same object would see.
Experiments to try
- Call
list(cd)a second time on an exhaustedCountdown(3)and record the result, then explain which attribute made it empty. - Move the decrement before the value capture (
self.current -= 1thenvalue = self.current) and predict the new sequence; decide which order reads more clearly. - Construct
Countdown(0)and observe that the very firstnext()raisesStopIteration; check thatlistreturns[]without an error. - Replace
return selfwithreturn Countdown(self.current)in__iter__, then iterate the same object twice and compare with the original behavior.
Common mistakes
- Returning
selffrom__iter__on a class meant to be reused: the first loop drains the shared state, so the second loop over the same object sees an exhausted iterator. - Forgetting to raise
StopIterationat the end:list()cannot terminate and aforloop keeps calling__next__, which either spins forever or emits sentinel values that leak into the data. - Advancing the position in both
__iter__and__next__: the state moves twice per item, so values get skipped or duplicated. - Letting an unrelated
StopIterationescape from__next__: anyStopIterationleaving the method is read as normal exhaustion, so a nested failure must be converted to another exception type.
Practice: Easy
- Type the
Countdownclass into a file, runlist(Countdown(3)), and write down the returned list plus the value of the object'scurrentattribute afterwards. - Change the argument to
Countdown(1)andCountdown(0); predict each result before running. - Add
print(self.current)at the top of__next__and read the trace forCountdown(3); identify which call raisesStopIteration.
Practice: Medium
- Rewrite
Countdownso__iter__returns a freshCountdowniterator built from the stored start, and show that the same object now supports two complete passes. - Add a
reset()method that restoresself.currentto the stored start; state whyreset()makes a self-iterator reusable without changing__iter__. - Write a
Fibonacci(limit)iterator that yields values below a limit and then raisesStopIteration; verify it withlistand with aforloop.
Practice: Hard
- Split
Countdowninto a container holding the start value and a separate iterator class holding the position; verify that two passes over the container produce identical sequences and that the container never changes. - Write a
pair_iter(names, scores)iterator over two parallel lists that stops as soon as either list runs out; add assertions for equal and unequal lengths. - Build an iterator whose
__next__performs a fallible operation (such asint()on a string) and decide how to handle a bad item without letting an accidentalStopIterationfrom nested code masquerade as exhaustion; document the rule you chose.
Lesson checklist
- I can implement
__next__so it returns one value per call and raisesStopIterationat the correct point. - I can trace which attribute holds the iteration position at every step of
Countdown(3). - I can explain when
__iter__should returnselfand when it should return a new iterator. - I can test a custom iterator with
next(),list(), and aforloop before trusting it.
Remember
A custom iterator is a small state machine: `__next__` reads the position, returns one value, and advances, while `StopIteration` reports that the position is spent. Decide deliberately what `__iter__` returns: `self` for a one-shot iterator, a fresh object per call for a reusable container. Test both passes early, because a self-iterator that looks fine on the first loop silently yields nothing on the second.
Interview angles
What is the main purpose of **__iter__**?+
__iter__ is the method iter() calls to obtain an iterator from an object, and it must return an iterator. An iterator's own __iter__ returns self, which is what lets it act as both the iterable and the thing that advances.
What should you pay attention to when using **__next__**?+
__next__ is the method next() calls to produce the next value: it returns one item per call and raises StopIteration when no items remain. A for loop calls it repeatedly and treats StopIteration as the normal end of the loop.
How does **Iterator state** fit into this lesson?+
An iterator stores whatever state is necessary to know the next value. Each next() call advances that state exactly once.
Why does a second `list(cd)` call on the same exhausted `Countdown(3)` object return `[]`?+
__iter__ returns self, so the object is its own single iteration state. The first pass consumed self.current down to 0, and a second pass starts from that exhausted state until reset() or a fresh iterator object restores it.