+ 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))
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
+ 1
please copy to playground to see output.
we will then discuss.
It is tricky...
+ 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
+ 1
Tibor Santa
just wanted to ping youđ
+ 1
Thanks Tibor Santa, I got it know