lambda semantics in for loop

Martin v. Löwis martin at v.loewis.de
Sun Jan 5 07:50:33 EST 2003


henk at empanda.net (Henk Punt) writes:

> l[0](1) = 10
> l[1](1) = 10
> 
> It seems that the 'i' in the lambda binds to the last value of i in the
> for loop.

That interpretation is slightly incorrect. 'i' binds to the value of i
at the time of the call.

> Is this because 'i' is really a pointer and not the value of 'i' itself?.
> Please enlighten me!,

The expression in a lambda expression is not evaluated until the
lambda is called. At that point, the variables in the expression are
either bound (as parameters, like x), or free (like i). Both kinds of
variables are evaluated when the expression is evaluated; the variable
i evaluates to the value that i has, at the time of evaluation.

> How do I modify the example so that I would get my expected semantics.

You want i to be evaluated at the time of lambda expression
creation. The only way to achieve this is through a default argument, as in

  lambda x, current_i = i: x + current_i

Here, the default argument is evaluated when the lambda expression is
produced. It is a common pattern to name the parameter of the lambda
expression like the variable one wants to evaluate, so you could write

  lambda x, i = i: x + i

HTH,
Martin




More information about the Python-list mailing list