+ 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.

3rd Jun 2018, 4:35 PM
Yusuf
Yusuf - avatar
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.
3rd Jun 2018, 5:33 PM
VcC
VcC - avatar
+ 1
why is it 2*x,2*x,2*x and not 1*x,2*x,3*x(i=2)
3rd Jun 2018, 6:40 PM
Pulkit Kamboj
Pulkit Kamboj - avatar
+ 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.
3rd Jun 2018, 7:09 PM
VcC
VcC - avatar
0
@VcC, why the list is of 3 functoins [i*x,i*x,i*x], and not [0*x,1*x,2*x]?
3rd Jun 2018, 6:16 PM
Pulkit Kamboj
Pulkit Kamboj - avatar
0
@Pulkit Kamboj I think it isn't [i*x,i*x,i*x], it is [2*x,2*x,2*x].
3rd Jun 2018, 6:39 PM
Yusuf
Yusuf - avatar
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.
3rd Jun 2018, 6:51 PM
Yusuf
Yusuf - avatar
0
Ok, thanks Joseph Hardrock
4th Jun 2018, 2:12 PM
Pulkit Kamboj
Pulkit Kamboj - avatar