questions about functions inside a function

Duncan Booth duncan.booth at invalid.invalid
Mon Jul 16 14:06:26 CEST 2007

"fdu.xiaojf at" <fdu.xiaojf at> wrote:

> What I want is, the value of i should be bounded to the anonymous
> function. And the output should like this:
> for f in a:
>      print f()
> 0
> 1
> 4
> 9
> How to achieve this?

Use default arguments when defining your function: default arguments are 
evaluated when the function is defined, bound arguments get the current 
value of the variable at the point when it is referenced during the call.

Also, since you give your function a name anyway ('b') you might as well 
use a named function as being clearer than using lambda:

>>> a = []
>>> for i in range(4):
	def b(i=i):
		return i**2

>>> for f in a:


More information about the Python-list mailing list