How to create a list of functions depending on a parameter?

enzo michelangeli enzomich at
Tue May 26 05:32:05 EDT 2009

Thanks guys. So far I had only come out with

f = [eval('lambda x: x+'+str(j)) for j in range(3)]

...which I hated because, as everybody knows, eval is evil :-)


On May 26, 5:20 pm, Arnaud Delobelle <arno... at> wrote:
> "Diez B. Roggisch" <de... at> writes:
> > You need to capture n into the closure of the lambda:
> > f = [lambda x, n=n: x+j for j in xrange(n)]
> You mean  [lambda x, j=j: x+j for j in xrange(n)]
> Another way would be [(lambda j:lambda x: x+j)(j) for j in xrange(n)]
> Or more readably:
> def adder(n):
>     return lambda x: x+n
> [adder(j) for j in xrange(n)]
> --
> Arnaud

More information about the Python-list mailing list