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

Scott David Daniels Scott.Daniels at Acm.Org
Tue May 26 10:20:33 EDT 2009


enzo michelangeli wrote:
> Let's suppose I want to create a list of n functions of a single
> argument, returning the sum between argument and index in the list, so
> that e.g.:
> 
> f[0](10) will return 10
> f[3](12) will return 15
> 
> ...and so on. I had naively though of coding:
> 
>  f = [lambda x: x+j for j in range(n)]

OK, first, almost a joke (unless you really need what you say):
     f = [j.__add__ for j in range(n)]

And now the one various others are missing:

     def add(x, y):
         '''replace with the function you actually want'''
         return x + y

     f = [functools.partial(add, n) for n in range(0)]

--Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list