0

I started learning python 3.3 lately, and I'm currently playing with the different features. I tried the following:

L = [lambda x: x*i for i in range(3)]

And I expected it to return a list of 3 functions - the first one gets a number and returns 0, the second one gets a number and returns the same number itself, and third one gets a number x and returns 2x. Apparently all the functions in the list L returns 2x:

>>>L[0](4)
8
>>>L[1](-7)
-14
>>>L[2](3)
6

What am I missing? How is it different from:

L = [lambda x: x*0, lambda x: x*1, lambda x: x*2]

which works as expected?

amirbd89
  • 101
  • 2
  • 2
    This is because of different scopes. In first case when you call any of the functions it reads `i` at the moment of calling which already is `2` no matter which function you call, i.e. inner `i` equals to the outer `i`. – freakish Oct 04 '16 at 20:23
  • It's just returning `i * 2` for the numbers you're inputting – Rafael Oct 04 '16 at 20:23
  • 2
    @user2357112's target is good. Another highly related (almost dupe post) is http://stackoverflow.com/questions/6076270/python-lambda-function-in-list-comprehensions – Bhargav Rao Oct 04 '16 at 20:25

0 Answers0