1

Is it possible that when appending lists of function objects in Python 3, the order gets lost?

My understanding was that Python lists are ordered and indeed running

numbers = []

for i in range(10):

    numbers.append(i)

print(numbers)

returns [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] as expected.

If I append function objects however, like in this MWE:

functions = []

for k in range(10):

    def test():
        print('This is the %i th function.' %k)

    functions.append(test)

and call functions[2]() I get This is the 9 th function.

Can somebody make sense of this odd behaviour?

Ben
  • 465
  • 2
  • 6
  • 17

1 Answers1

2

A function closure does not capture the value of a variable when it is defined, it captures the name of the variable.

Thus, the function you have stored in functions[2] references k. When you call it, it will show you the value of k when it is called, not when it was defined.

donkopotamus
  • 22,114
  • 2
  • 48
  • 60