[Tutor] lambda in a loop

Kent Johnson kent37 at tds.net
Wed Nov 16 23:46:00 CET 2005

Christian Wyglendowski wrote:
>>-----Original Message-----
>>From: tutor-bounces at python.org 
>> If I have this code:

>> Obviously, the lambda is using "value" at the end of the loop (4),
>>rather than what I want, "value" during the loop (0,1,2,3).  
> Right.  I think the issue is that your lambda calls another funtion.
> However, the function isn't called until the lambda is called later,
> when value == 4.

No, the problem is not when the function is called, but when value is bound into the closure.

> I'd use a closure rather than a lambda. 

The original solution does use a closure. The problem is that variables are not bound into a closure until the scope of the variable exits. That is why using a separate factory function works - the closure is bound when the factory function exits which happens each time through the loop. In the case of closures in a loop the closure is not bound until exiting the scope containing the loop and all the closures are bound to the same value.


More information about the Tutor mailing list