+ 3
Behavior of Lambda in List Comprehension
Can you explain why the functions generated from this list comprehension use the multiplier from the last value in the iterator instead of the value from their iteration? https://code.sololearn.com/cFGzHiByppD0/?ref=app
5 Réponses
+ 7
I'm still trying to get my head around this, but the following seems to apply:
https://docs.python.org/3/faq/programming.html#why-do-lambdas-defined-in-a-loop-with-different-values-all-return-the-same-result
+ 4
SagaTheGreat💯 agree wrong but no error, so legit use
+ 3
hey, your syntax for lambda is wrong,
use like below,
triplers = [(lambda x: i * x)(i) for i in multipliers]
above code will create list of squared values, 1,4,9....
if you want 1 2 3 as output then you can try like below,
multipliers = [1,2,3]
triplers = [(lambda x: i)(i) for i in multipliers]
print(triplers)
or
multipliers = [1,2,3]
triplers = [i for i in multipliers]
print(triplers)
+ 2
David Ashton Thank you very much.
That makes sense; just seems odd that the lambda holds a reference to the variable from outer scope even though the scope is gone by execution of the function.
+ 2
SagaTheGreat💯 Thank you for your comment. In this instance, it is generating a list of functions rather than actually executing them so the invocation syntax doesn't apply within the list comprehension.