lambda strangeness??

Roel Schroeven rschroev_nospam_ml at fastmail.fm
Sun Feb 27 04:39:49 EST 2005


Alan Gauld wrote:
> 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?

You're picking it up not as y but as n, since n in the lambda is
evaluated when you call the lambde, not when you define it.

Or is that just a coincidence? And why did it work
> inside the for loop?

In the loop you are giving n exactly the values you intended it to have
inside the lambda. Check what happens when you use a different loop
variable:

>>> for i in range(5): print adds[i](0)

9
9
9
9
9

I guess you could something like this instead:

>>> adds=[]
>>> for n in range(10):
	def f(y, n=n): return y+n
	adds.append(f)

	
>>> adds[0](0)
0
>>> adds[0](5)
5
>>> adds[9](5)
14

-- 
"Codito ergo sum"
Roel Schroeven



More information about the Python-list mailing list