Lesson · Iteration Protocol
Iterable vs Iterator
73 min readIterable vs Iterator
An iterable can produce an iterator, and an iterator produces values until it raises `StopIteration`. This protocol is the mechanism behind `for`, comprehensions, unpacking, and many standard-library tools.
Learning goals
- Explain the difference between an iterable (hands out iterators) and an iterator (produces values and holds a position).
- Trace what
iter(values)returns and what eachnext(iterator)call does to that object's state. - Explain how a
forloop usesiter()andnext()and why it never shows theStopIterationit catches. - Predict which objects can be iterated twice and which give up their values after one pass.
- Catch
StopIterationdeliberately so an exhausted iterator becomes a controlled branch instead of a crash.
Mental model
The arrow chain is the whole protocol: iter(iterable) returns an iterator, each next(iterator) yields one value and advances the stored position, and StopIteration marks normal exhaustion. A for loop runs exactly this sequence on your behalf, and because the position lives in the iterator rather than in the loop, an iterator is one-shot while a container is not.
The container holds data; the iterator holds the position
iter() creates the cursor, next() advances it
Mental model
the same mechanism as a compact list
iterable --iter()--> iterator --next()--> value ... StopIteration
Core idea
Two job descriptions sit behind one loop: an iterable knows how to hand out an iterator, and an iterator knows how to hand out values one at a time. iter() is the conversion step, next() is the advance step, and StopIteration is the ordinary end-of-data signal that for catches for you. One-shot consumption, reusable containers, and the hidden loop protocol all follow from that split of responsibilities.
Iterable
An iterable is an object that can be looped over: it implements __iter__, which returns a fresh iterator, or the older sequence protocol through __getitem__. Lists, tuples, strings, dicts, sets, ranges, and generator objects are all iterables, and the for loop, unpacking, and comprehensions each begin by asking one for an iterator.
Iterator
An iterator is the object that actually produces values: it implements __next__, which returns the next item or raises StopIteration when the data ends, and __iter__, which returns the iterator itself so it can be used wherever an iterable is expected. It also owns the iteration position, which is why advancing it consumes it.
iter()
iter(target) asks target for an iterator by calling its __iter__ method and returns that iterator. When the object has no __iter__ but does define __getitem__, iter() falls back to the older sequence protocol; an object with neither raises TypeError.
next()
next(iterator) returns the next value from an iterator and moves its stored position forward. When no values remain it raises StopIteration rather than returning a value.
StopIteration
An iterator signals normal exhaustion by raising StopIteration. A for loop catches this internally and stops without exposing it as an error.
One-shot iterators
An iterator is generally consumed as it advances. After exhaustion, reuse requires a new iterator from the original iterable or regeneration of the data.
Reusable iterables
A reusable iterable returns a fresh iterator each time iter() is called. Containers such as lists behave this way, unlike iterator objects that return themselves.
The for loop protocol
A for loop calls iter() on the iterable, repeatedly calls next() on the iterator, and stops when StopIteration signals exhaustion. The syntax hides this protocol but follows it consistently.
Walkthrough
values = [10, 20, 30]is the iterable; the list owns the data and can hand out a fresh iterator on everyiter(values)call.iterator = iter(values)is the object that holds the position; the list itself never remembers how far iteration has gone.- The three
next(iterator)calls print10,20, and30; each call advances the same iterator one step, which is why the values arrive without any index. - The fourth
next(iterator)raisesStopIteration; thetryblock lets theexceptbranch printiterator exhaustedinstead of ending the script with a traceback. Predict before running: the fourth call's outcome and the line that reports it.
Experiments to try
- Create two iterators with
a = iter(values)andb = iter(values), then alternatenext(a)andnext(b); record the sequence, then repeat with one shared iterator and explain the difference. - Consume
iteratorto exhaustion and callnext(iterator)inside atry/except StopIteration; call it again and note that it keeps raising rather than restarting. - Run
next(values)directly and read theTypeError; state which object the call expected and which one it received. - Loop over
valuestwice with twoforloops, then loop overiteratortwice; compare the four outputs and say which object remembers position.
Playable lesson
Lab: Iterable/iterator state machine
Show iter() creating an iterator and repeated next() calls advancing state until StopIteration.
The lab should ask for a prediction before each state transition. Include a reset action and at least one intentionally misleading case.
Iterable / iterator state machine
Iterable: values (never remembers position)
The list is unchanged. Every `iter(values)` hands out a brand new cursor.
Iterator: it (owns the cursor)
not created yet: run iter(values)
Predict first
The 4th `next(it)` on a 3-item iterator: what happens?
Predict first
What does `next(values)` do, with `values` still a plain list?
Predict first
After two `next(it)` calls, a `for` loop over the same `it` starts at which value?
The trap button shows why the cursor must come from `iter()`: a list has no `__next__`.
Common mistakes
- Calling
next()on the iterable:next(values)raisesTypeErrorbecause a list has__iter__but no__next__; the call belongs on the object returned byiter(). - Treating containers and iterators as the same kind of thing: two
forloops overvaluesboth start at10, while two loops over a shared iterator continue from wherever the first one stopped. - Letting
StopIterationescape a manualnext()call: exhaustion is normal, but without a handler the traceback makes it look like a failure. - Assuming a partly used iterator forgets its position: after two
nextcalls, aforloop over the same iterator starts at30, not at10.
Practice: Easy
- Run
values = [10, 20, 30]and printlist(iter(values))twice; explain why both lines print all three values, whileit = iter(values); list(it); list(it)prints three and then none. - Call
next(iter(values))three times in a row; state which object each call advances and why the result never moves past10. - Call
next(values)and write down the exception type and message, then repair the call so it behaves like the worked example.
Practice: Medium
- Interleave two iterators from the same list (
a = iter(values),b = iter(values)) by alternatingnext(a)andnext(b); record the sequence, then repeat with a single shared iterator and compare. - Write a
safe_next(it)helper that returnsNonewhen the iterator is exhausted and the next value otherwise; name the exception it must catch and why the caller no longer needs atry. - Consume two values from
iteratorand then loop over it withfor; afterwards loop overvalueswithforand compare the two outputs.
Practice: Hard
- Write
take(iterable, n)that returns up tonitems as a list usingiter()andnext(), stopping cleanly when the source runs out; test it with a list longer thannand one shorter. - Compare a list and a generator expression across two
forloops by printing all four results; explain which object returns itself fromiter()and what that implies for reuse. - Design a state diagram for the worked example with three states (fresh, producing, exhausted) and label every transition with
iter(),next(), orStopIteration; verify each edge in the REPL.
Lesson checklist
- I can say which object holds the iteration position and which object hands out fresh iterators.
- I can trace the worked example line by line through the
iter(),next(), andStopIterationchain. - I can predict whether a
forloop over a given object can run twice. - I can catch
StopIterationdeliberately instead of letting manualnext()calls crash.
Remember
An iterable knows how to create iterators; an iterator knows how to produce values and remembers where it stopped. `iter()`, `next()`, and `StopIteration` are the three moving parts, and the `for` loop is a wrapper around exactly that sequence. The split explains the practical rules: containers restart, iterators do not, and manual `next()` calls need a handler for the normal end-of-data signal.
Interview angles
What is the main purpose of **Iterable**?+
An iterable is an object that can be looped over: it implements __iter__, which returns a fresh iterator, or the older sequence protocol through __getitem__. The for loop, unpacking, and comprehensions each begin by asking an iterable for an iterator.
What should you pay attention to when using **Iterator**?+
An iterator implements __next__, which returns the next item or raises StopIteration when the data ends, and __iter__, which returns the iterator itself. It owns the iteration position, which is why advancing it consumes it.
How does **iter()** fit into this lesson?+
iter(target) asks target for an iterator by calling its __iter__ method and returns that iterator. When the object has no __iter__ but does define __getitem__, iter() falls back to the older sequence protocol; an object with neither raises TypeError.
Why does `next(values)` raise `TypeError` even though `values` is a perfectly usable list?+
next() asks for an object with a __next__ method; a list implements __iter__ but is not itself an iterator. The call belongs on the object returned by iter(values).