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. -- https://mail.python.org/mailman/listinfo/python-list