If you run this code with Python 2.7,
i = 5
x = [1, 2, 3, 4]
y = [i*i for i in x if i % 2 == 0]
The value of i
is changed to 4. But how?
If you run this code with Python 2.7,
i = 5
x = [1, 2, 3, 4]
y = [i*i for i in x if i % 2 == 0]
The value of i
is changed to 4. But how?
I think you're using Python 2.7, which leaks the variables defined in the comprehension. On the last iteration the i
in the loop is equal to 4, and the name i
from the comprehensionthen shadows the global name once control leaves the comprehension.
Python 3 doesn't do that anymore, though, so you should update.
That's a Python 2 specific limitation. Variables inside list comprehension have their own scope in Python 3:
Python 3.7.2 (default, Mar 11 2019, 11:54:40)
[GCC 7.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> i = 5
>>> x = [1, 2, 3, 4]
>>> y = [i*i for i in x if i == 2]
>>> i
5