0

The following code:

funcs = []
for a in [1,2,3]:
    funcs.append(lambda: a)

print(funcs[0](), funcs[1](), funcs[2]())

outputs the following:

3 3 3

However, if we define each lambda function not via a for loop but "by hand" as so:

funcs = []
funcs.append(lambda: 1)
funcs.append(lambda: 2)
funcs.append(lambda: 3)

print(funcs[0](), funcs[1](), funcs[2]())

then the output is

1 2 3

The latter output is the one I would expect as "correct". Why is it that doing the same in a for loop results in something different?

qamo
  • 1
  • 2

0 Answers0