Autogenerate functions (array of lambdas)

Hrvoje Niksic hniksic at xemacs.org
Thu Sep 6 05:27:03 EDT 2007


Chris Johnson <effigies at gmail.com> 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.



More information about the Python-list mailing list