Sub topic 3
What a for loop really does
This chapter assumes you know that iter() and next() exist and that a class can define __iter__ and __next__. It also assumes you are comfortable with try/except. Here you will see how for uses those pieces, so you can predict its behavior in edge cases.
A for loop is a while loop in disguise
Python has no separate machinery for for. The statement calls iter() once, then calls next() repeatedly until StopIteration is raised. These two snippets behave the same:
colors = ["red", "green"]
for color in colors:
print(color)
else:
print("no break")
iterator = iter(colors)
while True:
try:
color = next(iterator)
except StopIteration:
print("no break")
break
print(color)Both print red, green, then no break. The else branch of a for is the code that runs when StopIteration ends the loop. A break in the body leaves the while before that branch is reached, and the same thing happens in a real for.
Watching the calls happen
A class that prints inside its two methods shows the exact order of calls:
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__Three facts follow from this trace:
__iter__runs exactly once, before the first item.__next__runs one more time than there are items. The last call is the one that raisesStopIteration.- The loop variable is bound to whatever
__next__returned, and the body runs after that.
Why `__iter__` returns self on iterators
The for statement always calls iter() first, even when you hand it an iterator. That means iterators must also have an __iter__ method, and by convention it returns self. Because of this, iter(it) is it holds for any well-behaved iterator.
This has a visible consequence. A loop over an iterator does not restart it, so it can pick up where an earlier loop stopped:
it = iter([1, 2, 3, 4])
for x in it:
if x == 2:
break
print(list(it)) # [3, 4]The break left the iterator after it had produced 2. The list() call then received the same iterator and consumed the rest. Doing the same with the list itself would start from the beginning each time, because every iter(my_list) creates a new iterator object.
| You loop over | `iter()` returns | A second loop |
|---|---|---|
| A list, tuple, dict, or string | A new iterator each time | Starts from the beginning |
| An iterator or generator | The same object | Continues, or yields nothing if exhausted |
What iter() accepts
iter(obj) tries these options in order:
- It looks up
__iter__on the type ofobjand calls it. The lookup skips the instance, so assigningobj.__iter__ = ...on an instance has no effect. - If there is no
__iter__but the type defines__getitem__, Python builds an iterator that callsobj[0],obj[1], and so on. It stops whenIndexErroris raised. - Otherwise it raises
TypeError.
The second rule is the older sequence protocol, and it still works:
class Squares:
def __getitem__(self, index):
if index >= 4:
raise IndexError
return index * index
print(list(Squares())) # [0, 1, 4, 9]Here Squares has no __iter__, yet list() can consume it. You will rarely write this on purpose, but it explains why some old classes work in loops without defining __iter__.
For the first rule, whatever __iter__ returns must itself be an iterator, meaning it has __next__. Returning a plain list is a common mistake:
class Bag:
def __init__(self, items):
self.items = items
def __iter__(self):
return self.items # wrong: a list is iterable, not an iterator
try:
for item in Bag([1, 2]):
pass
except TypeError as error:
print(error) # iter() returned non-iterator of type 'list'The fix is return iter(self.items). Later chapters show a neater version that uses yield.
Where StopIteration is and is not caught
A for loop catches StopIteration only when it comes from the __next__ call that the loop itself makes. If the body raises it, nothing special happens, and the exception propagates like any other:
def body_raises():
for x in [1, 2]:
raise StopIteration
try:
body_raises()
except StopIteration:
print("escaped the loop")The same applies to code that calls next() itself. A bare next(it) on an exhausted iterator raises StopIteration. You can pass a default to avoid that:
it = iter([])
print(next(it, "empty")) # emptyInside a generator function, an uncaught StopIteration is converted to RuntimeError, so it cannot silently end the generator early. A later chapter covers this rule.
Other places that use the same protocol
for is the most visible user of the protocol, but many constructs share it:
- Comprehensions and generator expressions
list(),tuple(),set(),sorted(),sum(),min(),max(),any(),all()- Unpacking, as in
a, b = pairandfirst, *rest = items zip(),enumerate(),map(),filter(), andstr.join()- The
inoperator, but only when the type has no__contains__
The last point is a fallback. x in obj first tries obj.__contains__(x). If that is missing, Python loops over obj and compares each item. On a generator, in therefore consumes items up to the match:
it = iter([1, 2, 3, 4])
print(3 in it) # True
print(list(it)) # [4]The items 1, 2, and 3 are gone after the test. Treat in on an iterator as a destructive operation.
The loop variable and the iterator are separate things
A for loop assigns each value to the loop variable using ordinary assignment. This has three effects:
- The name stays bound after the loop ends, holding the last value. If the iterable was empty, the name is never assigned.
- Assigning to the loop variable inside the body does not change the iteration, because the next value comes from
next(), not from the variable. - Any assignment target is allowed, so
for key, value in d.items()andfor i, (a, b) in enumerate(pairs)use normal unpacking.
for n in range(3):
n = n * 10 # affects only this pass of the body
print(n) # 20, the last value assigned by the bodyThe last value from range(3) was 2, but the body then rebound n to 20 on that final pass.
Mutating a collection while looping over it
The list iterator stores a position, not a copy. Each next() reads the list at the current index and then increases the index. If the body removes items, the list shifts left and the iterator skips an item:
nums = [2, 4, 6, 8]
for n in nums:
if n % 2 == 0:
nums.remove(n)
print(nums) # [4, 8]All four numbers are even, yet two survive. On the first pass index 0 held 2, which was removed. The items then shifted, so index 1 held 6, and 4 was never visited.
Dictionaries and sets protect against this differently. They record their size and raise an error when it changes during iteration:
d = {"a": 1}
try:
for key in d:
d["b"] = 2
except RuntimeError as error:
print(error) # dictionary changed size during iterationTo change a collection while walking it, iterate over a copy such as for n in list(nums):, or build a new collection with a comprehension.
Common errors and what they mean
| Error or symptom | Likely cause |
|---|---|
| `TypeError: 'int' object is not iterable` | `iter()` found neither `__iter__` nor `__getitem__` on the object. A frequent cause is `for i in len(items)` where `range(len(items))` was meant. |
| `TypeError: iter() returned non-iterator` | `__iter__` returned something without `__next__`. |
| A second loop over the same object does nothing | The object is an iterator that is already exhausted. |
| Items missing after a `break` and a later loop | The iterator was partly consumed, and the later loop resumed from there. |
| A list loop skips items | The body modified the list during iteration. |
Exercises
Exercise
What does this code print, and why? it = iter("abcd") for ch in it: if ch == "b": break for ch in it: print(ch)
Show answer
It prints c and then d, each on its own line. The first loop consumes "a" and "b" and breaks on "b". The second loop calls iter(it), which returns the same iterator, so it continues from "c" and ends when StopIteration is raised.
Exercise
How many times is _iter called and how many times is next_ called when a for loop runs over an object that is its own iterator and produces 3 items? What happens to the else clause if the body runs break on the second item?
Show answer
_iter is called once and next is called 4 times (three values plus the call that raises StopIteration). If the body runs break on the second item, next_ has been called only twice and the else clause does not run, because the loop was left without StopIteration.