Python 2.7.11 GCC 4.8.4 Getting weird results when define a nested function in a loop and store them in a list x = list() for i in xrange(5): def FUN(): print i x.append(FUN) Calling functions from list using index works fine: for i in xrange(5): print x[i] x[i]() # prints 0 1 2 3 4 Calling function using iteration through the sequence yields wrong results, despite current function (f) changes: for f in x: print f f() # prints 4 4 4 4 4
Note also that your first example worked only because your loop variable was named i. If you used, say, 'j', you'd get the same result as in your second example. This is because the closure is over the named variable, and both in your definition loop and your print loop, that variable is the 'i' in the global namespace.