Variable leaking in list comprehensions and for loops

suggest change

Consider the following list comprehension.

In Python 2 the name leaks, so this prints 2:

i = 0
a = [i for i in range(3)]
print(i) # Outputs 2

In Python 3 a comprehension has its own scope, so i stays 0:

i = 0
a = [i for i in range(3)]
print(i) # Outputs 0

A for loop still has no private scope for its iteration variable:

i = 0
for i in range(3):
    pass
print(i) # Outputs 2

To avoid issues with leaking variables, use new variables in list comprehensions and for loops as appropriate.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents