Sub topic 6
What happens to the loop variable
This chapter assumes you can write a basic for loop, use range(), and know what a function is. It explains where the loop variable lives, what value it holds after the loop, and the mistakes that follow from that.
The loop variable is an ordinary variable
A for statement does not create a private scope for its variable. Python binds the name in the enclosing scope, which is the module, or the function if the loop is inside one. The name is rebound on every iteration. When the loop ends, it keeps the last value it was given.
for i in range(3):
pass
print(i) # 2: the loop variable is still bound after the loop
for j in range(0):
pass
# print(j) would raise NameError, because the body never ranIn the first loop, i ends as 2, the last item range(3) produced. In the second loop, the range is empty, so Python never assigns j. Reading it afterwards raises NameError.
Reassigning the variable inside the body
Assigning to the loop variable inside the body affects only the rest of that iteration. On the next pass, Python binds the name to the next item from the iterator, and your change is lost.
for n in range(3):
n = n * 10
print(n) # 0, 10, 20
print(n) # 20The loop is driven by the iterator, not by the variable. Changing n does not skip items or alter the sequence. If you want to change the sequence, change what you iterate over.
Using the value after the loop
Because the name survives, you can read it after the loop. This is occasionally useful, for example to learn where a search stopped.
numbers = [3, 8, 12, 5]
for position, value in enumerate(numbers):
if value > 10:
break
print(position, value) # 2 12Be careful, though. If the loop finishes without break, the names hold the last item, which may not mean what you expect. If the list is empty, the names do not exist at all. Code that depends on the variable after the loop should check that the loop ran, or use the else clause, covered in a later chapter.
Common mistakes
- Using the variable when the iterable may be empty. A
NameErrorappears only for empty input, so tests with sample data can miss it. Set a default before the loop if you need one. - Reusing a name. If a variable called
itemorialready holds something you need, a loop with the same name overwrites it. - Late binding in closures. A function created inside a loop looks up the variable when it is called, not when it is defined.
funcs = []
for k in range(3):
funcs.append(lambda: k)
print([f() for f in funcs]) # [2, 2, 2], not [0, 1, 2]
funcs = []
for k in range(3):
funcs.append(lambda k=k: k)
print([f() for f in funcs]) # [0, 1, 2]All three lambdas share the one name k, which is 2 by the time they run. The second version uses a default argument, which is evaluated at definition time, to capture each value.
Summary of the rules
| Situation | State of the loop variable after the loop |
|---|---|
| Loop ran to the end | Holds the last item |
| Loop left with `break` | Holds the item current at the break |
| Iterable was empty | Never assigned, so `NameError` if unbound before |
| Body reassigned it | Reset to the next item on each pass |
Exercise
What does this code print, and why? for x in range(4): x += 10 followed by print(x).
Show answer
It prints 13. The last item from range(4) is 3, so on the final pass x is bound to 3 and then increased to 13. Nothing rebinds x afterwards, and the loop variable stays bound after the loop ends.
Exercise
A function runs for line in lines: and then returns line. What goes wrong when lines is empty, and how can you prevent it?
Show answer
line is never assigned, so the return statement raises UnboundLocalError (a kind of NameError). Prevent it by assigning a default such as line = None before the loop, or by checking if not lines first.