lambda strangeness??
Roel Schroeven
rschroev_nospam_ml at fastmail.fm
Sun Feb 27 10:30:13 EST 2005
Alan Gauld wrote:
> On Sun, 27 Feb 2005 09:07:28 +0000 (UTC), Alan Gauld
> <alan.gauld at btinternet.com> wrote:
>
>
>>>>>adds = [lambda y: (y + n) for n in range(10)]
>>>>>adds[0](0)
>>
>>9
>>
>>>>>for n in range(5): print adds[n](42)
>>
>>...
>>42
>>43
>
>
>>the for loop... It seems to somehow be related to the
>>last value in the range(), am I somehow picking that up as y?
>
>
> Further exploration suggests I'm picking it up as n not y, if
> that indeed is what's happening...
Your intent is to create lambda's that are equivalent to
adds[0] = lambda y: y + 0
adds[1] = lambda y: y + 1
etc.
but what actually happens is that you get lambda's that are equivalent to
adds[0] = lambda y: y + n
adds[1] = lambda y: y + n
etc.
which obviously depend on the value of n at the moment you call the lambda.
--
"Codito ergo sum"
Roel Schroeven
More information about the Python-list
mailing list