Python 2
The n
variable used in the list comprehension is the same n
as is passed in.
The comprehension sets it to 1
, 2
, and then finally 3
.
Instead, change it to
arr = [0 for _ in range(n)]
or (surprisingly!)
arr = list(0 for n in range(n))
Python 3
This has been fixed.
From the BDFL himself:
We also made another change in Python 3, to improve equivalence
between list comprehensions and generator expressions. In Python 2,
the list comprehension "leaks" the loop control variable into the
surrounding scope:
x = 'before'
a = [x for x in 1, 2, 3]
print x # this prints '3', not 'before'
This was an artifact of the original implementation of list
comprehensions; it was one of Python's "dirty little secrets" for
years. It started out as an intentional compromise to make list
comprehensions blindingly fast, and while it was not a common pitfall
for beginners, it definitely stung people occasionally. For generator
expressions we could not do this. Generator expressions are
implemented using generators, whose execution requires a separate
execution frame...
However, in Python 3, we decided to fix the "dirty little secret" of
list comprehensions by using the same implementation strategy as for
generator expressions. Thus, in Python 3, the above example (after
modification to use print(x) :-) will print 'before'.