Python Language Common Pitfalls Variable leaking in list comprehensions and for loops

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

Consider the following list comprehension

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

This occurs only in Python 2 due to the fact that the list comprehension “leaks” the loop control variable into the surrounding scope (source). This behavior can lead to hard-to-find bugs and it has been fixed in Python 3.

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

Similarly, for loops have no private scope for their iteration variable

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

This type of behavior occurs both in Python 2 and Python 3.

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



Got any Python Language Question?