+ 2

Understanding List comprehension of anonymous functions

>>> def cm(): ... return[lambda x:i*x for i in range(3)] >>> for m in cm(): ... m(1) ... 2 2 2 # I was expecting 0, 1, 2 # I dig in further more >>> a,b,c = [i for i in range(3)] >>> a 0 >>> b 1 >>> c 2 # List comprehension of integer worked as per my understanding >>> a,b,c = [lambda x:i*x for i in range(3)] >>> a <function <listcomp>.<lambda> at 0x04CE5198> >>> a(1) 2 >>> a(2) 4 >>> a(0) 0 # I dont understand why is each input multiplied by 2

11th Jun 2018, 8:13 AM
Gopal Gautam
Gopal Gautam - avatar
1 Réponse
11th Jun 2018, 8:28 AM
Gopal Gautam
Gopal Gautam - avatar