Weird lambda behaviour in list comprehension [dupl

2019-07-05 00:57发布

问题:

This question already has an answer here:

  • Weird behavior: Lambda inside list comprehension 6 answers

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?

回答1:

lambdas bind variables themselves, not the values that they had. i is changed to 2 at the end of the list comprehension, so all the lambdas 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).