Does the loop variable of a list comprehension leak into the surrounding scope in Python 3?
No. In Python 3 a comprehension has its own scope, so its loop variable does not leak. A normal for loop does leave its variable behind. In Python 2, list comprehensions did leak.
Explain it simply
A comprehension is like a small exam room with its own rough sheet. Whatever you scribble there is thrown away when you leave. A plain for loop works on your own desk, so the last value stays there afterwards.
Example
x = "outer"
squares = [x * x for x in range(4)]
print(squares) # Output: [0, 1, 4, 9]
print(x) # Output: outer
for y in range(3):
pass
print(y) # Output: 2
try:
print(z)
except NameError:
print("z is undefined") # Output: z is undefinedThe comprehension's x is a separate variable, so the outer x keeps its value. The for y loop leaves y as 2.
A walrus assignment inside a comprehension is the exception: the name it binds does leave the comprehension and appears in the enclosing scope.
What to say in the interview
"In Python 3 list, set and dict comprehensions and generator expressions run in their own function-like scope, so the iteration variable stays local to them. A regular for loop does not create a scope, so its variable survives after the loop. Python 2 list comprehensions leaked, which was fixed in Python 3."
Common mistakes
- Relying on a loop variable after the loop when the loop may run zero times; the name may never be defined.