+ 3
List lambda
Hi! def cm(): return [lambda x: i*x for i in range(3)] for m in cm(): print m(1) Output:222 And my question is about lambda. The expression in this [lambda x: i*x for i in range(3)] Work as lambda x: 2*x for i in range(3)] And return 222 I do not understand why that After all range(3)=0,1,2 but no 2,2,2 Why it returns 2,2,2?
2 Antworten
+ 17
If we unpack the list comprehension and lambda function, cm() rougly looks like
def cm():
def f(x):
return i*x
funcs = []
for i in range(3):
funcs.append(f)
return funcs
Now the issue seems clearer: All three functions in the list refer to the same variable i, which is not local to them. So when these fuctions are called, 2, the last value of i coming from iterating over range(3), is used. For more experiments, we can try
def cm():
def f(x):
return i*x
funcs = []
for i in range(3):
funcs.append(f)
i = 10
return funcs
This time output is three 10s, as 10 is the last value of i. A quick way to avoid this is to save i as a variable local to the lambdas:
def cm():
return [lambda x, j=i: j*x for i in range(3)]
A variant of this is also in the Python FAQ:
https://docs.python.org/3/faq/programming.html#why-do-lambdas-defined-in-a-loop-with-different-values-all-return-the-same-result
+ 4
Maybe this is what you want to do🤔
https://code.sololearn.com/cJ070QKCnhBy