0

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?

Nijesh
  • 49
  • 8
  • 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? @poke – Nijesh Apr 28 '15 at 06:41
  • 1
    See the linked question, it’s the same thing: `i` is lexically scoped, so when the lambda is executed only then it evaluates `i`, at which point the loop has completely run. – poke Apr 28 '15 at 10:30

0 Answers0