lambda trouble

Bruce Wolk fake at not-a-real-address.net
Fri Mar 19 13:13:25 EST 2004


Gandalf wrote:
> 
> Darabos Daniel wrote:
> 
>> And it surprised me a little. I was expecting to see 0, 1, 2, 3, 4.
>> After some brainwork I now kind of understand what happens and I even
>> found a solution like this:
>>
> Well, it is not suprising. In a lambda expression, everything after the 
> : is symbolic. It is compiled,
> not evaluated. You can use a named function instead of an unnamed one:
> 
> [GCC 3.3.3 [FreeBSD] 20031106] on freebsd5
> Type "help", "copyright", "credits" or "license" for more information.
>  >>> def p(x):
> ... print x
> ...
>  >>> l = []
>  >>> for i in range( 5 ):
> ... def func():
> ... p(i)
> ... l.append( func )
> ...
>  >>> for k in l:
> ... k()
> ...
>  >>> l
> [<function func at 0x81a4f0c>, <function func at 0x81a4f44>, <function 
> func at 0x81a4f7c>, <function func at 0x81a4fb4>, <function func at 
> 0x81ae02c>]
>  >>>
> 
> You have different functions. However, in every function, the name 'i' 
> is not a local name. (Python has only two levels: local and global.)
> Here is another solution. However, it uses eval. Probably, it is not the 
> fastest one.
> 
> def p(x):
> print x
> 
> l = []
> for i in range( 5 ):
> l.append(eval("lambda: p( %s )"%i))
> 
> for k in l:
> k()
> 
> 
> Udv,
> 
> Laci
> 
> 
It is really even simpler:

 >>> def p(x):
	print x

 >>> l=[lambda i=i: p(i) for i in range(5)]
 >>> for k in l:
	k()

0
1
2
3
4
 >>>




More information about the Python-list mailing list