fun with lambdas

Robert Kern robert.kern at gmail.com
Thu Oct 20 23:21:35 EDT 2005


Juan Pablo Romero wrote:
> Hello!
> 
> given the definition
> 
> def f(a,b): return a+b
> 
> With this code:
> 
> fs = [ lambda x: f(x,o) for o in [0,1,2]]
> 
> or this
> 
> fs = []
> for o in [0,1,2]:
>     fs.append( lambda x: f(x,o) )
> 
> I'd expect that fs contains partial evaluated functions, i.e.
> 
> fs[0](0) == 0
> fs[1](0) == 1
> fs[2](0) == 2
> 
> But this is not the case :(
> 
> What is happening here?

Namespaces. The functions are looking up o at runtime. In both cases, o
is bound to the last object in [0,1,2] once the iteration is finished.

Try this (although I'm sure there are better ways):

In [4]: fs = [lambda x, o=o: f(x, o) for o in [0,1,2]]

In [5]: fs[0](0)
Out[5]: 0

In [6]: fs[0](1)
Out[6]: 1

In [7]: fs[0](2)
Out[7]: 2

-- 
Robert Kern
rkern at ucsd.edu

"In the fields of hell where the grass grows high
 Are the graves of dreams allowed to die."
  -- Richard Harter




More information about the Python-list mailing list