+ 10

Why this code output is 222.

def cm(): return[lambda x:i*x for i in range(3)] for m in cm(): print(m(1),end='') #output=222 ,but why.

8th May 2018, 4:30 PM
Maninder $ingh
Maninder $ingh - avatar
2 Respostas
+ 3
As we can see function returns something like 'a list of lambdas', so in line: # for m in cm(): We're taking as though first lambda and assign it to 'm', then: # print (m(1), end='') We're calling lambda with argument equals 1. Well, let's check what is going on 2nd line in detail: # return [lambda x: i*x for i in range(3)] """ for i in range(3): #1 0*1 (i=0 * x=1) = 0 #2 . 1*1 (i=1 * x=1) = 1 #3. 2*1 (i=2 * x=1) = 2 """ it means that: lambda x(1) = 2, and function will return 2. As There are 2 lambdas left, the result will be '222'.
8th May 2018, 5:04 PM
MsJ
MsJ - avatar
+ 2
for I in range (3) creates 3 lambda functions keep in mind that they are not calculated till 3 lamda functions generated now i=2 and ur pass 1 to x so it's x:1*2 for three times and as in print line end is not escape char for newline ("\n") it is "" it prints 222 without newline
8th May 2018, 5:04 PM
Yugabdh
Yugabdh - avatar