lambda-funcs problem

Stéphane Larouche stephane.larouche at polymtl.ca
Wed Sep 19 09:29:25 EDT 2007


Ryan Ginstrom <software <at> ginstrom.com> writes:
> How about:
> 
> >>> def make_adder(i):
> 	def adder(x):
> 		return x+i
> 	return adder
> 
> >>> funcs = [make_adder(i) for i in xrange(10)]
> >>> print [func(10) for func in funcs]
> [10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
> >>> 

Or if you want a one liner:

funcs = [(lambda i: lambda x: x+i)(i) for i in xrange(10)]

Stéphane




More information about the Python-list mailing list