lambda trouble

Karl Pflästerer sigurd at 12move.de
Fri Mar 19 20:19:52 CET 2004


On 19 Mar 2004, Darabos Daniel <- cyhawk at sch.bme.hu wrote:

>>>> def p( x ):
> ...     print x
> ...
>>>> l = []
>>>> for i in range( 5 ):
> ...     l.append( lambda: p( i ) )
> ...
>>>> for k in l:
> ...     k()
> ...
> 4
> 4
> 4
> 4
> 4

> And it surprised me a little. I was expecting to see 0, 1, 2, 3, 4.

The `i' in your code is bound to the global value of `i' which is 4.

> After some brainwork I now kind of understand what happens and I even
> found a solution like this:

>>>> def mylambda( fn, *args ):
> ...     return lambda: apply( fn, args )
[...]

> But I still feel a bit unsatisfied. Do you have some advice for me?

You have to bind the value of `i' in the lambda form; you did that with
your function definition but it can be done a bit simpler:

>>> funs = [lambda i=i: sys.stdout.write(str(i)+"\n") for i in range(4)]
>>> for f in funs:
...     f()
... 
0
1
2
3
>>>  

With the `i=i' the `i' in the lambda got bound.


   KP

-- 
      And has thou slain the Jabberwock?
          Come to my arms, my beamish boy!
      O frabjous day!  Callooh!  Callay!'
          He chortled in his joy.   "Lewis Carroll" "Jabberwocky"



More information about the Python-list mailing list