0
def count():
    fs = []
    for i in range(1, 4):
        def f():
             return i*i
        fs.append(f)
    return fs


f1, f2, f3 = count()
print(f1(), f2(), f3())

I'm learning Python, finding the result above is 9 9 9 instead of 1 4 9. I try to debug the code step by step, but in IDE I cannot get any extra information about <function count.<locals>.f at 0x0000000003987598> when appending functions to list. I wanna know what is the detail order of the code, especially when appending f() whether the value of the variable i would be recorded(i*i or 1*1 or some other circumstance). And what 's the significance of for i in range(1, 4)?

  • 1
    The inner `f` function gets a reference to `i`. So all your `f` use the same `i`, with whatever value it has at the time you call the `f`s – spectras Aug 09 '18 at 02:15
  • 1
    It is quite simple: the closure captures the *variable* `i` itself, not the value at the given moment. This is an example of "late-binding" closures. So think about it: what is the value of `i` when the for-loop is over, i.e. *when your list of functions returns*? – juanpa.arrivillaga Aug 09 '18 at 02:16
  • @juanpa.arrivillaga ok, this answer is explicit, thx – code-life balance Aug 09 '18 at 02:18
  • 1
    IOW, you've created 3 functions all that have a closure over the *same variable `i`*, and they do the exact same thing with that variable, so of course, they return the same value! Anyway, check out the linked duplicates above for more details. – juanpa.arrivillaga Aug 09 '18 at 02:19

0 Answers0