lambda strangeness??

Alan Gauld alan.gauld at btinternet.com
Mon Feb 28 03:55:52 EST 2005


On Sun, 27 Feb 2005 09:39:49 GMT, Roel Schroeven
<rschroev_nospam_ml at fastmail.fm> wrote:

> >>>>adds = [lambda y: (y + n) for n in range(10)]

> 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.

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

>>> adds = [lambda x, y=n: (x + y) for n in range(10)]

Works perfectly, thanks Roel.
I knew I'd got this to work in the past with a for loop
so I knew it should be possible in a comprehension. I
just forgot the default argument trick! And then confused myself
by coincidentally using n both inside and outside the LC, thus
apparently getting inconsistent results!

Thanks again,

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