What a for Loop Really Does: Python's Iterator Protocol
This article explains how every for loop in Python rests on the iterator protocol, distinguishes iterables from iterators, implements the protocol with classes and generators, and describes exhaustion, the sequence fallback and common iteration errors.
The loop for item in collection works in the same way with lists, strings, dictionaries, files, generators and objects defined by the programmer, although these types share no common base class. The present article examines the mechanism that makes this possible, the iterator protocol, which consists of two special methods and one exception. It distinguishes iterables from iterators, rebuilds the for loop from its parts, implements the protocol in a class and with a generator, and describes the behaviours that surprise programmers: exhausted iterators, objects that are iterable without declaring it and errors raised while iterating. A protocol of two methods that every loop, comprehension and built-in function understands is the secret weapon behind the uniformity of Python.
Iterables and Iterators
Two roles must be distinguished. An iterable is an object that can produce an iterator when the built-in function iter is applied to it, which calls its method __iter__. An iterator is the object that delivers the elements one at a time through __next__, called by the built-in function next, and signals the end by raising StopIteration.
numbers = [10, 20, 30]
iterator = iter(numbers)
print(type(iterator).__name__) # Output: list_iterator
print(next(iterator), next(iterator)) # Output: 10 20
print(next(iterator)) # Output: 30
try:
next(iterator)
except StopIteration:
print("exhausted") # Output: exhausted
print(iter(iterator) is iterator) # Output: True
print(next(iterator, "default")) # Output: default
The list is the iterable and the list_iterator is a separate object that remembers the position reached. Every iterator is also iterable, because its __iter__ returns the iterator itself, which is why an iterator can be used directly in a for loop. Once exhausted, an iterator stays exhausted: the documentation requires that, after raising StopIteration, every subsequent call raise it again, and the second argument of next provides a default value instead of the exception. These methods belong to the special methods described in the article devoted to the data model.
What a for Loop Does
The statement for item in iterable: body is equivalent, in its observable behaviour, to the following steps: obtain an iterator with iter(iterable), call next on it repeatedly, run the body with each value and stop when StopIteration is raised. Written by hand, the loop takes this form:
iterator = iter([1, 2, 3])
while True:
try:
item = next(iterator)
except StopIteration:
break
print(item)
# Output: 1
# Output: 2
# Output: 3
The interpreter does not literally execute a try statement, since a dedicated bytecode instruction advances the iterator, but the protocol is the same. Comprehensions, unpacking, sum, list, zip, in and every function that accepts "an iterable" follow these steps, so any object that implements the protocol works with all of them.
A Custom Iterable and Its Iterators
Role-playing games with instanced dungeons offer a precise image of the two roles: the dungeon is defined once, but each group that enters receives its own instance, with its own progress, and a group that has cleared its instance cannot clear it again. This means that an iterable should create a new iterator on every call to __iter__, so that several loops progress independently, whereas each iterator is consumed once. The analogy, however, stops at this point, because a game creates instances on request with a cooldown, whereas an iterable may create as many iterators as the program asks for, at any moment.
class Countdown:
def __init__(self, start):
self.start = start
def __iter__(self):
return CountdownIterator(self.start)
class CountdownIterator:
def __init__(self, current):
self.current = current
def __iter__(self):
return self
def __next__(self):
if self.current <= 0:
raise StopIteration
self.current -= 1
return self.current + 1
launch = Countdown(3)
print(list(launch), list(launch)) # Output: [3, 2, 1] [3, 2, 1]
print([(a, b) for a in launch for b in launch if a == b]) # Output: [(3, 3), (2, 2), (1, 1)]
once = CountdownIterator(3)
print(list(once), list(once)) # Output: [3, 2, 1] []
print(sum(Countdown(100)), 3 in Countdown(5)) # Output: 5050 True
The iterable Countdown can be traversed twice, and even by two nested loops at once, because each traversal receives a fresh CountdownIterator. The iterator used directly yields its values only the first time, and the second list receives nothing. Since Countdown implements the protocol, sum and the operator in work with it without further code.
Shorter Forms of the Protocol
Writing a separate iterator class is rarely necessary. A method __iter__ written as a generator function returns a new generator, which is an iterator, on every call. The built-in iter also accepts two older forms: objects that only define __getitem__ with indices starting at zero, and a callable followed by a sentinel value.
class Countdown:
def __init__(self, start):
self.start = start
def __iter__(self):
current = self.start
while current > 0:
yield current
current -= 1
print(list(Countdown(3))) # Output: [3, 2, 1]
class Squares:
def __getitem__(self, index):
if index >= 4:
raise IndexError(index)
return index * index
from collections.abc import Iterable
print(list(Squares())) # Output: [0, 1, 4, 9]
print(isinstance(Squares(), Iterable)) # Output: False
import io
stream = io.StringIO("alpha\nbeta\n\nignored\n")
print(list(iter(stream.readline, "\n"))) # Output: ['alpha\n', 'beta\n']
The generator version of Countdown removes the separate iterator class and keeps the independence of each traversal, as explained in the article devoted to yield. The class Squares is iterable through the sequence protocol, iter calls __getitem__ with 0, 1, 2 and so on until IndexError, yet isinstance with collections.abc.Iterable answers False, because that check looks only for __iter__; the documentation states that the only reliable test is to call iter. The two-argument form calls readline until it returns the sentinel, here the empty line, which turns any repeated call into an iterator.
Pitfalls of Iteration
The protocol is simple, but its interaction with exceptions, mutation and attribute lookup produces errors that are not obvious from the code. Six pitfalls are distinguished, which are the following:
- Consuming an iterator twice. An iterator passed to two functions is exhausted by the first; the second receives nothing and raises no error.
- Returning
selffrom an iterable. A container whose__iter__returnsselfbehaves as a single iterator, and nested loops over it interfere. StopIterationinside a generator. Since Python 3.7 (PEP 479), aStopIterationthat escapes a generator, for example from a barenext, is converted intoRuntimeError.- Mutating a collection while iterating. Adding keys to a dictionary during a loop over it raises
RuntimeError, and modifying a list silently skips or repeats elements. - Methods assigned to instances. Special methods are looked up on the type, so an
__iter__attached to an instance is ignored. - Trusting
isinstancewithIterable. Objects that iterate through__getitem__are not detected; callingiterinsidetryis the reliable test.
The third, fourth and fifth pitfalls are reproduced in the following example.
def first_items(iterables):
for iterable in iterables:
yield next(iter(iterable))
try:
list(first_items([[1], [], [3]]))
except RuntimeError as error:
print(error) # Output: generator raised StopIteration
counts = {"a": 1, "b": 2}
try:
for key in counts:
counts[key + key] = 0
except RuntimeError as error:
print(error) # Output: dictionary changed size during iteration
class Box:
pass
box = Box()
box.__iter__ = lambda: iter([1, 2])
try:
iter(box)
except TypeError as error:
print(error) # Output: 'Box' object is not iterable
The empty list makes next raise StopIteration inside the generator, which Python converts into RuntimeError instead of ending the generator silently; next(iter(iterable), None) avoids the problem. The dictionary refuses to grow during the loop, and the function attached to the instance is invisible to iter, which consults only the class.
Choosing an Implementation
Consequently, the form of the protocol depends on what the object represents and on how many times it must be traversed, as the following table summarizes.
| Situation | Recommended approach |
|---|---|
| A container that must support repeated and nested loops | __iter__ written as a generator |
| A stream that can be read only once | An iterator class, or a generator function |
| Repeated calls that end at a known value | iter(callable, sentinel) |
| Combining, slicing or grouping existing iterators | The functions of itertools |
| Testing whether an object is iterable | iter(obj) inside try, not isinstance |
| Reading the first element safely | next(iter(obj), default) |
The functions that combine iterators without materializing them are examined in the article devoted to itertools.
Conclusion
It is concluded that every for loop in Python rests on two methods, __iter__ and __next__, and on the exception StopIteration, and that the distinction between an iterable, which can be traversed many times, and an iterator, which is consumed once, explains most of the behaviour of loops. This magic extends to every object that implements the protocol, through a generator, a separate iterator class, __getitem__ or iter with a sentinel. Asynchronous code has its own version of the protocol, __aiter__ and __anext__, which belongs to the family of awaitable objects developed in a future article of this series.