I'm playing with lambda functions inside of list comprehension, and found some weird behaviour
x = [(lambda x: i) for i in range(3)]
print(x[0](0)) #print 2 instead of 0
print(x[1](0)) #print 2 instead of 1
print(x[2](0)) #print 2
Can someone explain why the result is not that I expect?
lambda
s bind variables themselves, not the values that they had. i
is changed to 2
at the end of the list comprehension, so all the lambda
s refer to i
at that point, and thus refer to 2.
To avoid this, you can use the default argument trick:
[lambda x,i=i:i for i in range(3)]
This binds the value of i
in the default argument (which is evaluated at function definition time).