+ 3

Wierd list comprehension and lambda

The code is: def list_func(): return [lambda x:i*x for i in range(3)] for f in list_func(): print (f(2), end='') So, I expect it will print out: 024 as if the list of lambda functions returned from list_func() would be [lambda x:0*x, lambda x:1*x, lambda x:2*x] But the actual output is 444, it seems that the list of lambda functions is [lambda x:2*x, lambda x:2*x, lambda x:2*x] The example without lambda: def list_func(): return [i*2 for i in range(3)] for f in list_func(): print (f, end='') Will output 024 as expected. Anyone could shed some light on why the first example output is 444? Thanks!

10th Jul 2017, 3:05 AM
BĂ ng Tứ Cường
BĂ ng Tứ Cường - avatar
1 Answer
+ 4
Oh, I found this: https://stackoverflow.com/questions/6076270/JUMP_LINK__&&__python__&&__JUMP_LINK-lambda-function-in-list-comprehensions Tomasz Gandor answered my question in his post. Turned out this relates to closure.
10th Jul 2017, 4:00 AM
BĂ ng Tứ Cường
BĂ ng Tứ Cường - avatar