[EMAIL PROTECTED] wrote: > The following code: > > def functions(): > l=list() > for i in range(5): > def inner(): > return i > l.append(inner) > return l > > > print [f() for f in functions()] > > > returns [4,4,4,4,4], rather than the hoped for [0,1,2,3,4]. I presume > this is something to do with the variable i getting re-bound every time > we go through the loop
free variables bind to *names*, not objects. all your functions will refer to the name "i" in "function"'s scope, which is bound to a 4 when the loop has finished. you can use the default argument mechanism to explicitly bind to an object instead of a name: def functions(): l=list() for i in range(5): def inner(i=i): return i l.append(inner) return l </F> -- http://mail.python.org/mailman/listinfo/python-list