+ 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

22nd Jun 2018, 12:45 AM
1_coder
5 Answers
+ 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
22nd Jun 2018, 1:51 AM
David Ashton
David Ashton - avatar
+ 4
SagaTheGreat💯 agree wrong but no error, so legit use
22nd Jun 2018, 2:33 AM
Abdur-Rahmaan Janhangeer
Abdur-Rahmaan Janhangeer - avatar
+ 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)
22nd Jun 2018, 1:44 AM
$¢𝐎₹𝔭!𝐨𝓝
$¢𝐎₹𝔭!𝐨𝓝 - avatar
+ 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.
22nd Jun 2018, 2:47 AM
1_coder
+ 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.
22nd Jun 2018, 2:49 AM
1_coder