+ 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
1 Answer
+ 2
I got my answer from stackoverflow. Thanks to Tomasz Gandor of Stackoverflow.
https://stackoverflow.com/questions/6076270/JUMP_LINK__&&__python__&&__JUMP_LINK-lambda-function-in-list-comprehensions/6076304