lambda strangeness??

Alan Gauld alan.gauld at btinternet.com
Sun Feb 27 04:07:28 EST 2005


I was playing with lambdas and list compregensions and came
across this unexpected behaviour:

>>> 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
44
45
46
>>> adds[0](0)
4

Can anyone explain the different answers I'm getting?
FWIW the behaviour I expected was what seems to happen inside 
the for loop... It seems to somehow be related to the 
last value in the range(), am I somehow picking that up as y?
If so why? Or is that just a coincidence? And why did it work
inside the for loop?

Puzzled,

Alan G.
Author of the Learn to Program website
http://www.freenetpages.co.uk/hp/alan.gauld



More information about the Python-list mailing list