Weird Lambda Behaviour In List Comprehension
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
Solution 1:
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 inrange(3)]
This binds the value of i
in the default argument (which is evaluated at function definition time).
Post a Comment for "Weird Lambda Behaviour In List Comprehension"