Lambda evaluation

Joshua Ginsberg listspam at flowtheory.net
Thu Oct 6 17:40:44 EDT 2005


That's a damned elegant solution -- thank you...

However in trying to simplify my problem for presentation here, I think
I oversimplified a bit too much. Try this one:

>>> d = {}
>>> for x in [1,2,3]:
...     d[x] = lambda *args: args[0]*x
...
>>> d[1](3)
9

The lambda is going to have to take arbitrary arguments, so I can't
specify x=x before the arbitrary arguments (otherwise, it gets
overridden) and I can't specify it afterward (syntax error). :-/ Thanks!

-jag

On Thu, 2005-10-06 at 16:27 -0400, Jp Calderone wrote:
> On Thu, 06 Oct 2005 16:18:15 -0400, Joshua Ginsberg <listspam at flowtheory.net> wrote:
> >So this part makes total sense to me:
> >
> >>>> d = {}
> >>>> for x in [1,2,3]:
> >...     d[x] = lambda y: y*x
> >...
> >>>> d[1](3)
> >9
> >
> >Because x in the lambda definition isn't evaluated until the lambda is
> >executed, at which point x is 3.
> >
> >Is there a way to specifically hard code into that lambda definition the
> >contemporary value of an external variable? In other words, is there a
> >way to rewrite the line "d[x] = lambda y: y*x" so that it is always the
> >case that d[1](3) = 3?
> 
> There are several ways, but this one involves the least additional typing:
> 
>     >>> d = {}
>     >>> for x in 1, 2, 3:
>     ...     d[x] = lambda y, x=x: y * x
>     ... 
>     >>> d[1](3)
>     3
> 
> Who needs closures, anyway? :)
> 
> Jp




More information about the Python-list mailing list