Sub topic 8
Scope: why the loop variable does not leak
This chapter assumes you can write a basic list comprehension and know how a plain for loop behaves. You should also know the difference between a local and a global variable. Here you will see where a comprehension keeps its loop variable and how that differs from a for loop.
A loop variable in a plain for loop
A plain for loop does not create a new scope. Its loop variable is an ordinary variable in the surrounding code. It stays alive after the loop ends, and it overwrites any variable that had the same name.
x = "outer"
for x in range(3):
pass
print(x) # 2The loop reassigned x, so the original "outer" is gone. In large functions this kind of overwrite is easy to miss.
A comprehension has its own scope
In Python 3, a comprehension runs in its own scope. The loop variable exists only inside that scope. It does not touch a variable of the same name outside.
x = "outer"
squares = [x * x for x in range(3)]
print(squares) # [0, 1, 4]
print(x) # outerThe x inside the comprehension is a different variable from the outer x. After the comprehension finishes, the inner x is discarded and the outer x still holds "outer".
This applies to list, dict, and set comprehensions and to generator expressions. It is the main reason many people prefer a comprehension to a loop that builds a list by hand.
data = [3, 1, 2]
doubled = {n: n * 2 for n in data}
unique = {n % 2 for n in data}
try:
print(n)
except NameError as error:
print(error) # name 'n' is not definedSince n never existed outside the comprehensions, reading it raises a NameError.
What the scope looks like
The diagram shows the two scopes. The comprehension can read names from the enclosing code, but its loop variable stays inside.
Reading outer variables
The inner scope can still read names defined outside. This is how a comprehension uses a threshold, a prefix, or a helper function.
limit = 5
numbers = [2, 7, 4, 9]
small = [n for n in numbers if n < limit]
print(small) # [2, 4]Here limit is not defined inside the comprehension, so Python looks it up in the enclosing scope. Reading works. The scope boundary only stops the loop variable from escaping.
Common errors
Relying on the old leaking behavior is the usual mistake. In Python 2, a list comprehension did leak its loop variable. Old code and old tutorials may assume this. In Python 3, the following code fails:
values = [n for n in range(3)]
print(n) # NameError: name 'n' is not definedIf you want the last value, compute it directly, for example with values[-1], or use a plain loop.
A second error is expecting to assign to an outer variable from inside a comprehension. The loop variable is always local to the comprehension. A comprehension cannot rebind an outer name through its for clause.
Summary of the difference
| Construct | Own scope | Loop variable after it ends |
|---|---|---|
| `for` loop | No | Still defined, holds the last value |
| List comprehension | Yes | Not defined |
| Dict comprehension | Yes | Not defined |
| Set comprehension | Yes | Not defined |
| Generator expression | Yes | Not defined |
Exercise
What do the two print calls show? x = 10 total = [x + 1 for x in range(3)] print(total) print(x)
Show answer
The first print shows [1, 2, 3], because the comprehension's own x takes the values 0, 1, and 2. The second print shows 10, because the comprehension's x lives in its own scope and does not overwrite the outer x.
Exercise
A colleague writes evens = [n for n in range(10) if n % 2 == 0] and then uses n on the next line to get the last even number. Why does this fail in Python 3, and what is a fix?
Show answer
The loop variable n exists only inside the comprehension's scope, so using it afterward raises NameError. Use evens[-1] to get the last even number.