Sub topic 8
Scope: Why the Loop Variable Does Not Leak
What this chapter assumes
You should be comfortable with for loops, range, and building lists, dicts, and sets. You should also know the basic comprehension forms from earlier chapters, including the trailing if filter. This chapter covers the scope rules behind them: which names a comprehension can see, which names it creates, and where those names go when it finishes.
A scope is the region of a program where a name is defined. When Python meets a name, it looks it up in a fixed order of scopes. Most surprises with comprehensions come from not knowing which scope a name belongs to.
The behavior
In Python 3, the loop variable of a comprehension exists only inside the comprehension.
x = "outer"
squares = [x * x for x in range(3)]
print(squares) # [0, 1, 4]
print(x) # outerThe comprehension uses the name x as its loop variable, but that x is a separate variable from the module-level x. After the comprehension finishes, the outer x still holds "outer".
A for statement behaves differently. It has no scope of its own, so its loop variable is an ordinary variable in the surrounding scope.
x = "outer"
for x in range(3):
pass
print(x) # 2The loop overwrote x, and the last value stays behind after the loop ends. If the iterable is empty, the loop never assigns the name, so a name that did not exist before still does not exist afterward.
You can see the same isolation when a name is not defined anywhere else:
values = [j * 2 for j in range(3)]
try:
print(j)
except NameError as err:
print("NameError:", err) # NameError: name 'j' is not definedThe name j was never created in the module scope, so looking it up fails.
Which constructs have their own scope
The rule applies to every comprehension form in Python 3, plus generator expressions.
| Construct | Own scope for the loop variable | Loop variable visible afterward |
|---|---|---|
| `for` statement | No | Yes |
| List comprehension | Yes | No |
| Dict comprehension | Yes | No |
| Set comprehension | Yes | No |
| Generator expression | Yes | No |
Python 2 was inconsistent here. Its list comprehensions leaked the loop variable into the enclosing scope, while generator expressions, and dict and set comprehensions (which arrived in Python 2.7), did not. Python 3 removed the leak from list comprehensions so that all of them behave alike. If you read old code or old Stack Overflow answers that rely on the leak, treat them as Python 2 material.
How lookup works inside a comprehension
Conceptually, Python runs a comprehension as if it were a small function that is called once. The loop variable is a local variable of that function. Names that the comprehension only reads are found by the usual lookup order: local scope, then each enclosing function scope, then module scope, then built-ins.
This is why a comprehension can read outside variables without any special syntax:
factor = 3
scaled = [n * factor for n in range(4)]
print(scaled) # [0, 3, 6, 9]Here n is local to the comprehension, while factor is found in the module scope.
Reading an outer name is easy. Assigning is different. A plain assignment inside a comprehension would create a local name, so a comprehension cannot rebind outer variables by accident. The only deliberate exception is the assignment expression, covered below.
Why the design is a good one
Isolation protects you in three ways.
- A comprehension cannot overwrite a variable that other code relies on. You can reuse short names such as
i,x, oritemwithout checking what else exists nearby. - The comprehension is self-contained. You can read it without wondering whether later code depends on its leftover loop variable.
- Refactoring is safer. Moving a comprehension into or out of a function does not change the value of any surrounding variable.
Reusing a name is legal, but it is not always kind to the reader. In the first example, [x * x for x in range(3)] next to an outer string x works, but a different name such as n makes the code clearer.
Gotcha: the first iterable is evaluated outside
There is one detail in the lookup rules. The outermost iterable, the expression after the first in, is evaluated in the enclosing scope before the comprehension scope starts. Everything else, including later for clauses, conditions, and the output expression, is evaluated inside it.
This rarely matters in functions and modules. It matters in class bodies, because a class body does not act as an enclosing scope for the functions or comprehensions written inside it.
class Sizes:
base = [1, 2, 3]
factor = 10
doubled = [b * 2 for b in base]
try:
scaled = [b * factor for b in base]
except NameError:
scaled = None
print(Sizes.doubled) # [2, 4, 6]
print(Sizes.scaled) # NoneThe first comprehension works because base is the outermost iterable and is evaluated in the class body. The second fails because factor is read inside the comprehension scope, which cannot see class-level names. The fix is to move factor to module level, compute the list in a function, or build it with a plain loop.
Gotcha: closures capture the variable, not the value
The loop variable lives in the comprehension's scope, so a function created inside the comprehension closes over that variable, not over the value from one iteration. All such functions share one variable per comprehension run. When they are called later, they see its final value. This is called late binding.
funcs = [lambda: n for n in range(3)]
print([f() for f in funcs]) # [2, 2, 2]Each lambda returns the current value of n, and by the time you call them, n is 2. A plain for loop that builds lambdas has the same behavior.
To capture the value at each step, pass it as a default argument. Defaults are evaluated when the lambda is created.
fixed = [lambda n=n: n for n in range(3)]
print([f() for f in fixed]) # [0, 1, 2]Be aware that this trick lets callers pass an argument that overrides n. When that matters, use functools.partial or a small factory function instead.
The one deliberate leak: assignment expressions
A walrus assignment (:=) inside a comprehension binds its target in the containing scope, not in the comprehension scope. This is deliberate. It lets you keep a computed value from a comprehension, such as the last item or a running result.
results = [(last := n * n) for n in range(4)]
print(results) # [0, 1, 4, 9]
print(last) # 9Python forbids using := to rebind the comprehension's own loop variable. [(n := 1) for n in range(3)] raises a SyntaxError. Assignment expressions are also not allowed in the iterable expression of a comprehension. A later chapter covers the walrus operator in detail. For now, remember that it is the exception to the isolation rule, so treat it carefully.
Common errors and how to read them
NameErrorafter a comprehension. You tried to use the loop variable afterward, as you could with aforloop. Compute what you need inside the comprehension, or use a loop if you need the variable.NameErrorinside a class body. The comprehension is trying to read a class variable from outside the first iterable. Move the data out of the class body or use a function.- Every closure returns the same value. This is late binding. Bind the value with a default argument or a factory.
- An outer variable seems unchanged. That is correct behavior. The comprehension used its own variable. Use a name that does not collide, or an explicit loop, if you meant to update the outer one.
- A variable you expected to leak is gone in a migrated program. The code was probably written for Python 2, where list comprehensions leaked.
Choosing a design based on scope
Scope rules can guide a choice between a comprehension and a loop. A comprehension is a good fit when the loop variable is a throwaway helper and the only thing you want is the resulting collection. A plain for loop is a better fit when you need the final value of the loop variable afterward, when you need to update outer variables step by step, or when the body has side effects. The readability chapter covers that decision in more depth.
Exercises
Exercise
What do the two print calls output, and why? x = 10 result = [x + 1 for x in range(3)] print(result) print(x)
Show answer
The first call prints [1, 2, 3] and the second prints 10. The comprehension's x is local to the comprehension, so the module-level x is never reassigned.
Exercise
A programmer writes checks = [lambda v: v > limit for limit in (1, 5, 9)], then calls each function with the value 6 and expects [True, True, False]. What does [c(6) for c in checks] actually return, and how can you fix the list so it behaves as expected?
Show answer
It returns [False, False, False], because all three lambdas share one limit variable, which is 9 after the comprehension finishes, and 6 > 9 is False. Fix it by binding the value when each lambda is created: checks = [lambda v, limit=limit: v > limit for limit in (1, 5, 9)]. Then [c(6) for c in checks] returns [True, True, False].
Exercise
In this class body, which comprehension raises NameError and why? class Pricing: rates = [1, 2, 3] tax = 5 a = [r for r in rates] b = [r + tax for r in rates]
Show answer
The comprehension for b raises NameError. Its output expression reads tax, a class variable, and a comprehension scope cannot see class-level names. The comprehension for a works because rates is the outermost iterable, which is evaluated in the class body.