+ 11

Python - Who explain me this code?

def cm(): return[lambda x:i*x for i in range(5)] for m in cm(): print(m(1),end="")

27th Jun 2020, 4:02 PM
Paolo De Nictolis
Paolo De Nictolis - avatar
1 Respuesta
+ 22
Here, lambda is set to only i*x and not the whole i*x for i in range (5) Since, lambda is an anonymous function, it will take only the final value of i. And this lambda function is being called 5(because of the for loop) times. The cm function is returning a list: [4*x, 4*x, 4*x, 4*x, 4*x] And then we are calling the lambda function using for loop. So, x will get replaced by 1 So we get 44444 4 shows the max value of i The no. of times of occurence of 4 shows that how many times the lambda function is called. For better understanding: def cm(): return[(lambda x:4*x) for i in range(5)] for m in cm(): print(m(1), end="") I hope this helps you!!! It's a bit confusing tho
27th Jun 2020, 4:32 PM
Namit Jain
Namit Jain - avatar