Can someone explain to me how this works please?? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

Can someone explain to me how this works please??

def cm(): return [lambda x : x*i for I in range(3)] for m in cm(): print(m(1)) #the output of this code is >>> 2 >>> 2 >>> 2 I know that this programme defines a function that returns a list of function (its length is given by the range() function) then calls then with the parameter assigned 1, but I don't understand why the output is the same because in the comprehensive list "i" should change when creating those function thus the output should be : 0 #x*0 (i=0) 1 #x*1 (i=1) 2 #x*2 (i=2) plz help!!!

7th Mar 2018, 6:18 PM
MedG
MedG - avatar
4 Answers
+ 6
https://eli.thegreenplace.net/2015/the-scope-of-index-variables-in-pythons-for-loops/ Here the main part is: def foo(): lst = [] for i in range(4): lst.append(lambda: i) print([f() for f in lst]) If you'd expect this to print [0, 1, 2, 3], no such luck. This code will, instead, emit [3, 3, 3, 3], because there's just a single i in the scope of foo, and this is what all the lambdas capture.
7th Mar 2018, 7:58 PM
Oma Falk
Oma Falk - avatar
+ 1
'''you must change from a list to a generator use round ( ) brackets instead of square [ ] brackets ''' def cm(): return (lambda x : x*i for i in range(3)) for m in cm(): print(m(1))
8th Mar 2018, 4:47 AM
Louis
Louis - avatar
0
still didn't quit understand that , if this how it works then why [I for I in range (4)] gives [0,1,2,3] and not [3,3,3,3]
7th Mar 2018, 9:43 PM
MedG
MedG - avatar
0
what you expect will result if you will change print(m(m))
20th Jul 2018, 6:33 PM
Pradeep Kumar Singh