Please explain this code | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Please explain this code

def cm(): return[lambda x:i*x for i in range(3)] for m in cm(): print(m(1),end='') In this code 'i' will have values 0,1 & 2. How 'x' will gets its value ? Output of this code is: 222

18th Oct 2020, 10:10 AM
Peter Parker
Peter Parker - avatar
1 Answer
+ 4
Cant tell ya exactly how, but single stepping through it, it creates a list of 3 lambda functions and passes 1 to them. In the lambda, there are x and i variables. Watching them through each iteration I can assume that the 1 in m(1) refers to x's value, and since i is in range of 3, 2 would be the max. In each iteration x = 1 and i = 2.
18th Oct 2020, 10:42 AM
Slick
Slick - avatar