+ 4
A Challenge Question in Python
def cm(): return[lambda x:i*x for i in range(3)] for m in cm(): print(m(1),end=") Output = 222 I couldn't understand what is happening in this question. Could you explain it? Thanks.
7 Answers
+ 2
cm() returns an array of 3 functions who return all i*x, with i being the same variable left as 2 in the last iteration.
+ 1
why is it 2*x,2*x,2*x and not 1*x,2*x,3*x(i=2)
+ 1
i is local but since it is referenced from the lambda it keep its existence outside of cm. and it keep the last value allocated.
0
@VcC, why the list is of 3 functoins [i*x,i*x,i*x], and not [0*x,1*x,2*x]?
0
@Pulkit Kamboj I think it isn't [i*x,i*x,i*x], it is [2*x,2*x,2*x].
0
@Pulkit Kamboj I think it is because i is a global variable within this statement. I mean it is happening like that:
1- [def func(x):
return i*x]->i is 0 at now.
2- [def func(x):
return i*x, def func(x):
return i*x]-> now i is 1.
3- [def func(x):
return i*x, def func(x):
return i*x, def func(x):
return i*x]-> now i is 2.
Since i is global i is simultaneously changing.
0
Ok, thanks Joseph Hardrock



