Functional programming gotcha

David C. Fox davidcfox at post.harvard.edu
Fri Oct 24 15:37:13 EDT 2003


David C. Fox wrote:

> Ed Schofield wrote:
> 
>> Hi all,
>>
>> I find this strange:
>>
>>
>>>>> flist = []
>>>>> for i in range(3):
>>
>>
>> ...     f = lambda x: x+i
>> ...     flist.append(f)
>> ...
>>
>>>>> [f(1) for f in flist]
>>
>>
>> [3, 3, 3]
>>
>>
>> What I expect is:
>>
>>
>>>>> [f(1) for f in flist]
>>
>>
>> [1,2,3]
>>
>>
>> Is this a bug in Python?  It happens on my builds of
>> Python 2.3 and 2.2.3.
> 
> 
> I guess the nested scopes changes in Python 2.1/2.2 (see 
> http://www.python.org/peps/pep-0227.html) apply to functions but not 
> loops.  

I take back that explanation.  The problem is that the i in the lambda 
*does* refer to the local variable i, whose value changes as you go 
through the loop, not to a new variable whose value is equal to the 
value of i at the time when the lambda was created.

The workaround is still the same:

> loops.  You can use the same workaround that people used to use because 
> of the lack of nested scopes:
> 
> f = lambda x, i = i: x + i
> 
> That way, the second, optional parameter has a default value which is 
> evaluated at the time the lambda is created.
> 

David





More information about the Python-list mailing list