2
funcs = []
for i in range(3):
    a = i
    func = lambda x: a
    funcs.append(func)

print [func(0) for func in funcs]

I would like this to print [0,1,2], instead it prints [2,2,2]. I see what's going on, the question is how do I circumvent this?

Set
  • 934
  • 6
  • 25

2 Answers2

3

You can get around this by binding a to the local scope of the lambda using a keyword argument:

funcs = []
for i in range(3):
    a = i
    func = lambda x, a=a: a
    funcs.append(func)
print [func(0) for func in funcs]

Output:

[0, 1, 2]
dano
  • 91,354
  • 19
  • 222
  • 219
0

This line:

func = lambda x: a

states that you want the function to return a no matter what you pass it.

So when you call the functions with the argument 0, it returns the value of a. Which is 2 after it exited from the for loop.

To circumvent that you would need to change the lambda function to:

func = lambda x: x

and change the following line:

print [func(0) for func in funcs]

to:

print [func(x) for x in range(3)]

Or bind a to the local scope of lambda as suggested by @dano.

shaktimaan
  • 11,962
  • 2
  • 29
  • 33
  • How can I augment this so that the output of each function I append to the list is dependent on the utterable? – Set Sep 17 '14 at 02:24