Python's strange list comprehension

def nrooks(n):
    #make board
    print n # prints 4
    arr = [0 for n in range(n)] # if 0 for n becomes 0 for x, it works fine
    print n # prints 3 instead of 4

nrooks(4)

Why does the second nbecome 3different from the given parameter?

+4
source share
1 answer

Python 2

The variable nused in understanding the list is the same nthat is passed.

Understanding sets the meaning 1, 2and then finally 3.

Instead, change it to

arr = [0 for _ in range(n)]

or (amazing!)

arr = list(0 for n in range(n))

Python 3

This is fixed.

From the BDFL itself :

Python 3, . Python 2, "" :

x = 'before'
a = [x for x in 1, 2, 3]
print x # this prints '3', not 'before'

; Python " " . , , . . , ...

Python 3 " " , . , Python 3 ( print (x):-) 'before'.

+4

All Articles