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

enzo michelangeli enzomich at gmail.com
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 :-)

Enzo

On May 26, 5:20 pm, Arnaud Delobelle <arno... at googlemail.com> wrote:
> "Diez B. Roggisch" <de... at nospam.web.de> 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