0
Help understanding this code output!
Input: def cm(): return[lambda x:i*x for i in range(3)] for m in cm(): print(m(1),end=") Output: 222
4 Answers
+ 1
You have a typo in your code here. it is end=''(two single quotation matks) , not end=" (one double quotation mark).
"cm" routine is a little bit tricky
----> [lambda x:i*x for i in range(3)]
it creates 3 lambda functions (range(3) gives us a sequence from 0 to 2).
This basically returns the last instance of i (2) taken from the range which turns into this:
lambda x:2*x and accepts an argument from a loop cycle (m(1)) --> x: 2*1 = 2
Having three lambda functions with the same arguments, we've got three similar results each time.
+ 1
stephanie
You have just to rewrite lambda function in this code in a canonical way to see the nuance:
lambda x:i*x for i in range(3) ---> (labmda x:i*x) for i in range(3)
Note, that lambda has no list argument to iterate through, that is why it takes a global variable passed to the routine (m(1)) --> 1
The code creates thee lambda functions according to range(3) but does not 'calculate them' and every time the i variable increases until it gets equal to 2.
When you call your for loop, you get all lambda functions calculated and all of them accept i as a parameter. But i is already equals to 2 and is not recalculating during the lambda function evaluating.
Sorry for a clumsy explanation - I hope you've got the idea.
0
thank you thank you @strawdog! This is really helpful. Also, this might be a stupid question but why does that return just the last instance of i(2) taken from the range? Is it an instance of recursive functions?
0
Ohh I see now. I think I have it down. Thank you again!!