fun with lambdas

Juan Pablo Romero jpablo.romero at gmail.com
Thu Oct 20 23:15:16 EDT 2005


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?


Nevertheless, this code does work

fs = [ eval("lambda x: f(x,%d)" % o) for o in [0,1,2,3]]

Thanks.

   Juan Pablo



More information about the Python-list mailing list