Functional programming gotcha

Terry Reedy tjreedy at udel.edu
Fri Oct 24 19:34:40 EDT 2003


"Ed Schofield" <schofield at ftw.at> wrote in message
news:Pine.LNX.4.33.0310242013060.3754-100000 at tethys.ftw.at...
>
> 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]

Others have given the solution, but let's think about the why of it.
If a function in a dyanamic language (one that allows runtime
construction of functions) has a free variable (one not set within the
function), the question arises "When do we get (capture) the value of
the variable?  At definition/construction time or at call/execution
time?  Or, to put it another way, what do we capture?  The (current)
value of the variable or its name (for later evaluation).  Either
could be what we want.

Python lets you choose which capture method (evaluation time) you
want.  Do nothing to get the name captured for later evaluation.  Or
put v=v in the arglist to capture the current value and give it the
same name (w=v, to use a new name, is legal too, of course).

Terry J. Reedy






More information about the Python-list mailing list