Functional programming gotcha
Robin Becker
robin at jessikat.fsnet.co.uk
Fri Oct 24 15:34:02 EDT 2003
In article <Pine.LNX.4.33.0310242013060.3754-100000 at tethys.ftw.at>, Ed
Schofield <schofield at ftw.at> writes
>
>Hi all,
>
>I find this strange:
>
>>>> flist = []
>>>> for i in range(3):
>... f = lambda x: x+i
try using f = lambda x,i=i: x+i ie bind at the definition point
>... 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.
>
>Replacing the lambda function by a named function, as in
>
>flist = []
>for i in range(3):
> def f(x):
> return x + i
> flist.append(f)
>
>[f(1) for f in flist]
>
>gives the same result.
>
>I have a workaround (of sorts) adapted from the Python tutorial:
>
>>>> def make_incrementor(n):
>... return lambda x: x + n
>...
>>>> flist = [make_incrementor(i) for i in range(3)]
>>>>
>>>> [f(1) for f in flist]
>[1, 2, 3]
>>>>
>
>but I'd prefer the flexibility of the first approach. Any ideas?
>
>Any explanations for why Python does this? Any justifications for why
>Python _should_ do this? Who believes this is a bug?
>
>Kind regards,
>Ed Schofield
>
--
Robin Becker
More information about the Python-list
mailing list