lambda - strange behavior

Jussi Piitulainen jpiitula at ling.helsinki.fi
Fri Sep 20 12:30:05 EDT 2013


Kasper Guldmann writes:

> I was playing around with lambda functions, but I cannot seem to
> fully grasp them. I was running the script below in Python 2.7.5,
> and it doesn't do what I want it to. Are lambda functions really
> supposed to work that way. How do I make it work as I intend?
> 
> f = []
> for n in range(5):
>     f.append( lambda x: x*n )
> 
> assert( f[4](2) == 8 )
> assert( f[3](3) == 9 )
> assert( f[2](2) == 4 )
> assert( f[1](8) == 8 )
> assert( f[0](2) == 0 )

It's not the lambda, it's the for. All five functions share the one n,
whose value the for changes in each iteration so that the last value
remains in force after the loop.

There's a trick: f.append( lambda x, n=n: x*n ). Now the lambda gets
to remember the value of the n of the for as the default value of its
own local n.



More information about the Python-list mailing list