lambda-funcs problem
Marc 'BlackJack' Rintsch
bj_666 at gmx.net
Wed Sep 19 07:56:19 EDT 2007
On Wed, 19 Sep 2007 04:39:44 -0700, dmitrey.kroshko wrote:
> I need to create a Python list of lambda-funcs that are dependent on
> the number of the ones, for example
>
> F = []
> for i in xrange(N):
> F.append(lambda x: x + i)
>
> however, the example don't work - since i in end is N-1 it yields x+
> (N-1) for any func.
>
> So what's the best way to make it valid?
The variable is bound to the name `i` when the lambda function is
created not to the value that `i` had at that time. The idiomatic way is
to use a default value for an argument because those are evaluated at
definition time of functions::
F.append(lambda x, i=i: x + i)
Ciao,
Marc 'BlackJack' Rintsch
More information about the Python-list
mailing list