0

Lambda function

Why the ouput is 102 and not 45 as well as x(=3)+i(=41) = 44? list=[] for i in range (100): list.append(lambda x:x+i) print (list [42](3)) but when i run a loop, the result is expected for i in range (100): print (list[i](3))

23rd Dec 2019, 2:40 PM
Hlad
Hlad - avatar
2 Respuestas
+ 2
It will work if you do : lambda x, i = i : x + i Because in the loop, the value of i changes. If you 'fix' the value by assigning a local variable i to... i it will work.
23rd Dec 2019, 2:43 PM
Théophile
Théophile - avatar
0
oh, great, TYSM
23rd Dec 2019, 2:47 PM
Hlad
Hlad - avatar