parameters to lambda's executed at run time.

Diez B. Roggisch deets at nospam.web.de
Tue May 6 06:17:54 EDT 2008


wyleu wrote:

> I'm trying to supply parameters to a function that is called at a
> later time as in the code below:
> 
> llist = []
> 
> for item in range(5):
>     llist.append(lambda: func(item))
> 
> def func(item):
>     print item
> 
> for thing in llist:
>     thing()
> 
> which produces the result
> 
> IDLE 1.2.1
>>>> ================================ RESTART
>>>> ================================
>>>>
> <function <lambda> at 0xb716356c>
> <function <lambda> at 0xb71635a4>
> <function <lambda> at 0xb71635dc>
> <function <lambda> at 0xb7163614>
> <function <lambda> at 0xb716364c>
>>>> ================================ RESTART
>>>> ================================
>>>>
> 4
> 4
> 4
> 4
> 4
>>>>
> 
> How can one allocate a different parameter to each instance of the
> function rather than all of them getting the final value of the loop?

That's a FAQ. Python creates a closure for you that will retain the last
value bound. To prevent that, you need to create a named paramter like
this:

lambda item=item: func(item)

That will bind the current item value at the lambda creation time.

Diez



More information about the Python-list mailing list