lambda semantics in for loop

Denis S. Otkidach ods at strana.ru
Sun Jan 5 07:56:52 EST 2003


On 5 Jan 2003, Henk Punt wrote:

HP> >>> l = []
HP> >>> for i in range(10):
HP> ...     l.append(lambda x: x + i)
[...]
HP> It seems that the 'i' in the lambda binds to the last value
HP> of i in the
HP> for loop.
HP> Is this because 'i' is really a pointer and not the value of
HP> 'i' itself?.
HP> Please enlighten me!,

i inside lambda is a global variable.  When you call it i equals
to 9.

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

Use class with __call__ method or factory function relying on
nested scopes.

HP> Should I copy 'i' to force the creation of a new object?, If
HP> so how would
HP> this work in the case where i is a string. I've tried to
HP> coerce python
HP> into making a deepcopy of a string so that id(s) !=
HP> id(copy(s)) but I've
HP> not been able to do that also.

Certainly, you can create a copy with "lambda x, i=i: x+i".

-- 
Denis S. Otkidach
http://www.python.ru/      [ru]






More information about the Python-list mailing list