Chris Johnson <[EMAIL PROTECTED]> writes:

> What I want to do is build an array of lambda functions, like so:
>
> a = [lambda: i for i in range(10)]

Use a factory function for creating the lambdas.  The explicit
function call will force a new variable binding to be created each
time, and the lambda will refer to that binding rather than to the
loop variable binding, which is reused for all loop iterations.  For
example:

def makefn(i):
    return lambda: i

>>> a = [makefn(i) for i in xrange(10)]
>>> [f() for f in a]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

The alternative is to explicitly import the value into the lambda's
parameter list, as explained by others.
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to