0

I tried to create different functions by the following code:

a = []

for i in range(5):
    a.append(lambda: i)

print(a)

and it showed it:

[<function <lambda> at 0x008DA100>, <function <lambda> at 0x008DA0B8>, <function <lambda> at 0x008DA148>, <function <lambda> at 0x008DA190>, <function <lambda> at 0x008DA1D8>]

I found that all the functions are different, but I found that it couldn't work later. Althought all the functions indicated to different address, but all the functions showed same number: 4;

a[0]()
4
a[1]()
4
a[2]()
4
a[3]()
4
a[4]()
4

Please tell me how to solve this problem.

LeeLin2602
  • 21
  • 2

1 Answers1

0

The reason why your lambdas are all returning 4 is because they all reference the same variable - i. And the value of i after the loop ends is 4. Since lambdas are executed when they are invoked - all your lambdas evaluate the same expression: i & therefore get the same result.

To get around this you need to bind the value of i as the time of lambda creation. To do that you can use a single-argument lambda with a default value:

a = []

for i in range(5):
    a.append(lambda x=i: x)

print(a[0]())

Which gives:

0

as expected.

rdas
  • 20,604
  • 6
  • 33
  • 46