I haven't used much functional programming core features like lambda
or map
, but I have recently found it useful. I am using the following lambda function and it is not generating the desired results.
def multiplier():
return [lambda x:x**i for i in range(10)]
print [m(2) for m in multiplier()] #output is [512, 512, 512, 512, 512, 512, 512, 512, 512, 512]
Why do I get this behaviour? Here in lambda, i
closes on the last value of list i.e 9 and hence when I pass parameter m(2) ..2**9 =512 is printed.
EDIT:
My exact question is as per my understanding , final output should be x**i; i ranging from 0 to 9 and where x=2 in my example. So why only i=9 is considered for all the 10 loops?
Can anyone explain as why is this happening?