+ 1

What is the output logic of this python snippet?

And how? def cm(): return[lambda x: i*x for i in range(3)] for m in cm(): print(m(1))

17th May 2020, 6:36 AM
Westworld
Westworld - avatar
5 Answers
+ 3
You can find a very detailed explanation here about the "why", actually the second answer from top: https://stackoverflow.com/questions/6076270/lambda-function-in-list-comprehensions Short version: the cm function returns a list of lambda functions. But the list comprehension is evaluated BEFORE the lambda, so the i variable reference will be the last value of range(3) in all lambda expressions, and that is 2. When you use these lambda functions and pass them 1 as argument, they all return 2*1
17th May 2020, 7:16 AM
Tibor Santa
Tibor Santa - avatar
+ 1
please copy to playground to see output. we will then discuss. It is tricky...
17th May 2020, 6:44 AM
Oma Falk
Oma Falk - avatar
+ 1
Lambda works in strange ways inside a list comprehension. I think we have discussed this before, check this thread too: https://www.sololearn.com/Discuss/2180319/?ref=app
17th May 2020, 6:50 AM
Tibor Santa
Tibor Santa - avatar
+ 1
Tibor Santa just wanted to ping you😂
17th May 2020, 6:51 AM
Oma Falk
Oma Falk - avatar
+ 1
Thanks Tibor Santa, I got it know
23rd May 2020, 6:21 AM
Westworld
Westworld - avatar