How to create a list of functions depending on a parameter?
Arnaud Delobelle
arnodel at googlemail.com
Tue May 26 05:20:41 EDT 2009
"Diez B. Roggisch" <deets 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