Variable leaking in list comprehensions and for loops
suggest changeConsider 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.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents