Sub topic 3
What a for loop really does
This chapter assumes you know how iterables and iterators differ, and that iter() and next() exist. It shows how a for loop uses them.
The loop is shorthand
A for loop does not know about lists, strings, or files. It works with any object that supports the iterator protocol. This loop:
names = ["Ada", "Grace"]
for name in names:
print(name)behaves like this:
names = ["Ada", "Grace"]
it = iter(names)
while True:
try:
name = next(it)
except StopIteration:
break
print(name)The steps are:
- Python calls
iter()on the object afterin, once, before the loop starts. This calls the object's__iter__method and returns an iterator. - At the start of each pass, Python calls
next()on that iterator, which calls its__next__method. - The value returned by
next()is assigned to the loop variable, and the body runs. - When
__next__raisesStopIteration, the loop ends quietly. The exception never reaches your code.
Watching the calls happen
This class prints a message whenever Python calls one of its protocol methods:
class Trace:
def __init__(self, n):
self.n = n
self.i = 0
def __iter__(self):
print("__iter__")
return self
def __next__(self):
print("__next__")
if self.i >= self.n:
raise StopIteration
self.i += 1
return self.i
for x in Trace(2):
print("body", x)The output is:
__iter__
__next__
body 1
__next__
body 2
__next____iter__ runs once. __next__ runs three times for two items, because the third call is the one that raises StopIteration and ends the loop.
Why iterators are also iterable
Trace.__iter__ returns self. This convention is why you can write for x in it when it is already an iterator. Calling iter() on an iterator gives you the same object back, so the loop continues from wherever the iterator stands.
it = iter([1, 2, 3])
next(it)
for x in it:
print(x) # prints 2, then 3Details that matter
- The
tryin the expanded loop wraps onlynext(it). AStopIterationraised inside the loop body is not treated as the end of the loop. It propagates as an ordinary exception. - A
forloop can have anelseclause. It runs when the iterator is exhausted and is skipped when the loop exits throughbreak. - The loop variable stays defined after the loop. If the iterator yielded nothing, the variable is never assigned.
- If the object has no
__iter__, Python falls back to the older sequence protocol, which calls__getitem__with 0, 1, 2 and so on untilIndexError. Otherwise it raisesTypeError: 'int' object is not iterable.
Other constructs follow the same protocol, including list(), sum(), unpacking, in, and comprehensions. Anything that works in a for loop works in these too.
Exercise
In a for loop over a list, how many times does Python call iter() on the list, and how many times does it call next() on the iterator if the list has 3 items?
Show answer
iter() is called once, before the first pass. next() is called 4 times: three calls return the items, and the fourth raises StopIteration, which ends the loop.