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

Diez B. Roggisch deets at nospam.web.de
Tue May 26 12:37:47 CEST 2009


Paul Rudin wrote:

> "Diez B. Roggisch" <deets at nospam.web.de> writes:
> 
>> enzo michelangeli schrieb:
>>> 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)]
>>>
>>> Unfortunately, each function in the list f[]() behaves as a closure,
>>> and f[k](p) does NOT return p+k but p+j (for whatever value j has at
>>> the moment: typically n, the last value assumed by j in the list
>>> comprehension loop).
>>>
>>> Is there a way of achieving my goal? (Of course, n is not a constant
>>> known in advance, so I can't manually unroll the loop.)
>>
>> You need to capture n into the closure of the lambda:
>>
>> f = [lambda x, n=n: x+j for j in xrange(n)]
>>
> 
> But be careful using such a technique with mutable arguments...

What makes "this technique" more susceptible to mutable argument issues than
any other function or method-definition?

Diez



More information about the Python-list mailing list