+ 5

How it works?

Hello! Why does the code print '222'? How it works? cm = [lambda x: i*x for i in range(3)] for m in cm: print(m(1), end='')

9th May 2018, 4:59 PM
Alexandr Shirapov
Alexandr Shirapov - avatar
3 odpowiedzi
+ 3
To me it looks like your cm should be equivalent to: cm = [ lambda x: 0*x, lambda x: 1*x, lambda x: 2*x ] but Python is making it equivalent to: cm = [ lambda x: 2*x, lambda x: 2*x, lambda x: 2*x ] and I don’t know why. If you wanted the first behavior, try defining a function with two arguments. Good luck there.
9th May 2018, 5:44 PM
Pedro Demingos
Pedro Demingos - avatar
+ 1
Yes, I, too, expected the behavior, as in your first example. I changed the code: cm = [] for i in range(3): def func(x): return i*x cm.append(func) for m in cm: print(m(1), end='') It seems to me that in this case the function variable is overwritten. Therefore, the last value is retained: cm = [lambda x: i*x for i in range(6)] for m in cm: print(m(1), end='') result: '555555' Very interesting)
10th May 2018, 3:09 AM
Alexandr Shirapov
Alexandr Shirapov - avatar
0
What is the output nums = [1,2,3,4,5] print (list___(____x:x%_==0,nums)) please help
14th May 2018, 2:06 AM
Narendra Kishore