Sub topic 6
What happens to the loop variable
This chapter assumes you can write a basic for loop, know what a function is, and understand that Python names are bound to objects. It covers where the loop variable lives, what value it has after the loop, and the bugs this causes. Run each snippet as its own script, because several reuse the names i, n, and x.
The loop variable is an ordinary name
A for loop does not create a new scope. The variable after the word for is a normal name in the enclosing scope. At module level it is a global. Inside a function it is a local. The loop assigns to it once per item, exactly as name = item would.
for i in range(3):
pass
print(i) # 2: the loop variable is still bound after the loopLanguages with block scope, such as C, Java, and JavaScript with let, discard the counter when the loop ends. Python keeps it. Only functions, classes, modules, and comprehensions (covered below) create scopes.
The value after the loop
What the name holds after the loop depends on how the loop ended.
| How the loop ended | Value of the loop variable afterwards |
|---|---|
| Ran to the end of a non-empty iterable | The last item produced |
| Left early with `break` | The item being processed when `break` ran |
| The iterable was empty | Unchanged: unbound, or whatever it held before |
| An exception escaped the loop | The item being processed when the exception was raised |
The empty case is the one that causes trouble. Inside a function, reading a name that was never assigned raises UnboundLocalError, which is a subclass of NameError.
def last_item(items):
for item in items:
pass
return item
print(last_item([1, 2, 3])) # 3
try:
last_item([])
except UnboundLocalError:
print("the body never ran, so item was never assigned")Relying on the variable after the loop is legal, and one pattern uses it on purpose: search with break, then use the item that stopped the loop. Handle the "not found" case explicitly so the empty or exhausted case cannot slip through.
def find_first_even(numbers):
for n in numbers:
if n % 2 == 0:
break
else:
return None # the loop finished without break
return n # n is the even number that triggered break
print(find_first_even([3, 5, 8, 9])) # 8
print(find_first_even([1, 3])) # NoneHere the else clause removes any doubt about whether n holds a match. Without it, a list with no even numbers would leave n holding the last odd number, and you might return it by mistake.
Overwriting an existing name
Because the loop variable is an ordinary name, it replaces any earlier binding with the same name. The loop gives no warning.
total = 100
for total in [1, 2, 3]:
pass
print(total) # 3, so the original 100 is goneThis is rarely intentional. It usually happens when a short name like i, item, or name is reused for a different purpose later in the same function or script. Two habits help:
- Choose loop variable names that describe the item, such as
orderorline, so they are unlikely to collide with other names. - Keep functions short, so a loop variable cannot be confused with an unrelated name far away.
The same problem occurs if you use a built-in name as the loop variable.
for list in [[1], [2]]:
pass
# list is now a sublist, so list("abc") would fail with TypeErrorAfter this loop, the built-in list is shadowed in that scope. Avoid built-in names such as list, str, max, and id.
Reassigning inside the body does not change the iteration
The loop takes the next item from the iterator, not from the variable. If you rebind the variable in the body, the new value lasts only until the next iteration assigns the next item.
for i in range(3):
print("start", i)
i = i * 10
print("changed", i)The output is:
start 0
changed 0
start 1
changed 10
start 2
changed 20Python assigns 1 to i on the second pass, even though the body set i to 0 the first time. Code that tries to skip ahead by changing the counter inside a for loop does not work in Python. If you need to control the step, change the range() arguments. If the stepping is irregular, use a while loop.
Targets can be more than one name
The target after for can be a tuple of names. Python unpacks each item into them, and every name follows the rules above.
prices = {"apple": 3, "pear": 5}
for fruit, price in prices.items():
pass
print(fruit, price) # pear 5Both fruit and price remain bound afterwards. If you only need part of each item, the convention is to name the unused part _. The name _ is still a real variable and is still left bound after the loop. It is a signal to readers, not a special syntax.
pairs = [(1, "a"), (2, "b")]
for number, _ in pairs:
print(number)The target may also be any assignable expression, such as for data["last"] in range(3). This is legal but rare, and most style guides discourage it.
Closures capture the variable, not the value
A common bug involves functions created inside a loop. A function defined in the loop body that mentions the loop variable looks the name up when the function is called, not when it is defined. All the functions therefore share one variable, and by the time you call them it holds the last value.
funcs = []
for n in range(3):
funcs.append(lambda: n)
print([f() for f in funcs]) # [2, 2, 2], not [0, 1, 2]To fix it, bind the current value as a default argument. Defaults are evaluated when the function is defined.
funcs = []
for n in range(3):
funcs.append(lambda n=n: n)
print([f() for f in funcs]) # [0, 1, 2]functools.partial achieves the same result without a default-argument trick.
Comprehensions have their own scope
List, set, and dictionary comprehensions and generator expressions are scoped differently from for statements. In Python 3, their loop variable exists only inside the comprehension.
squares = [x * x for x in range(4)]
print(squares) # [0, 1, 4, 9]
try:
print(x)
except NameError:
print("x does not exist outside the comprehension")This is a real difference from the for statement. If you convert a loop to a comprehension and later code reads the old loop variable, that code will break. Python 2 leaked the variable out of list comprehensions, so older tutorials may show different behavior.
Removing the variable
If you want a name gone after the loop, you can delete it with del.
for i in range(3):
pass
del iYou cannot do this safely if the loop might not have run, since del raises NameError or UnboundLocalError on an unbound name. Most programs never need del here. Choosing a descriptive name and not reading it after the loop is simpler.
Practical rules
- Treat the loop variable as meaningful only inside the body, unless you are using the
breaksearch pattern. - When you do read it after the loop, make sure the loop ran at least once, or guard with
elseor an explicit check. - Use distinctive names so a loop cannot overwrite a variable you still need.
- Never use a built-in name as a loop variable.
- In closures created inside a loop, bind the value you need explicitly.
Exercise
This script is meant to print the number of items followed by the last one. What does it print for report([4, 7, 9]), and what happens for report([])? Rewrite it so the empty case prints "no items" instead of failing.
def report(items):
count = 0
for item in items:
count += 1
print(count, item)
Show answer
For [4, 7, 9] it prints 3 9, because item keeps the last value after the loop. For [] the body never runs, so item is never assigned and print(count, item) raises UnboundLocalError. One fix is to check for emptiness first:
def report(items):
count = 0
for item in items:
count += 1
if count == 0:
print("no items")
else:
print(count, item)
Another fix is to test if not items: before the loop. Either way, the code no longer reads the loop variable when the loop did not run.