Interview Q&A / Python

IntermediateQuick answer1 min readUpdated 3 Oct 2026

Does the loop variable of a list comprehension leak into the surrounding scope in Python 3?

SHORT ANSWER

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

python
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 undefined

The 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.

#python#comprehensions#scope

Related questions

Practise more Python questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Python quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.