python 2.3's lambda behaves old fashioned

Fredrik Lundh fredrik at pythonware.com
Thu Apr 29 14:20:02 EDT 2004


Uwe Schmitt wrote:

> I just tried (Python 2.3)
>
>     li = [ lambda x: x*a for a in range(10) ]
>
> which results in
>
>     li[0](1) = 9
>     ...
>     li[9](1) = 9
>
> In order to achieve the intended result I had to fall back on the
> following trick:
>
>     li = [ lambda x,a=a: x*a for a in range(10)]
>
> which leads to the expected result.
>
> Any explanations ???

repeat after me:

free variables bind to names, default arguments bind to objects.
free variables bind to names, default arguments bind to objects.
free variables bind to names, default arguments bind to objects.
(etc)

</F>







More information about the Python-list mailing list