questions about functions inside a function

fdu.xiaojf at fdu.xiaojf at
Mon Jul 16 17:04:29 CEST 2007

Duncan Booth wrote:
> "fdu.xiaojf at" <fdu.xiaojf at> wrote:
>> In order to make sure all variables be larger than 0, I tried to created
>> constraint function like this:
>> cons = []
>> for i in range(N):
>>      c = lambda x: x[i] - 1e-10
>>      cons.append(c)
>> But when functions in cons are evaluated, the value in all functions are
>> all the same(N-1, which is the last value of i in the loop).
>> What I want is, when functions in cons be evaluated, every function
>> refers to a different variable in X.
> So pass i in as a default value:
> for i in range(N):
>    def c(x, i=i):
>        return x[i] - 1e-10
>    cons.append(c)

Thanks all of you have read or replied.

Both Duncan's and Steven's solution work well. Thanks!

I love python, not only because of the language itself, and also the so kind 

Xiao Jianfeng

More information about the Python-list mailing list