Understanding lambda in python and using it to pass multiple arguments

Talisin picture Talisin · Apr 27, 2012 · Viewed 194.4k times · Source

After reading everything I can find on lambda, I still don't understand how to make it do what I want.

Everyone uses the example:

lambda x, y : x + y

Why do you need to state both x and y before the :? Also how do you make it return multiple arguments?

for example:

self.buttonAdd_1 = Button(self, text='+', command=lambda : self.calculate(self.buttonOut_1.grid_info(), 1))

This works just fine. But the following code does not:

self.entry_1.bind("<Return>", lambda : self.calculate(self.buttonOut_1.grid_info(), 1))

It yields the error:

TypeError: () takes no arguments (1 given)

Answer

phipsgabler picture phipsgabler · Apr 27, 2012

Why do you need to state both 'x' and 'y' before the ':'?

Because a lambda is (conceptually) the same as a function, just written inline. Your example is equivalent to

def f(x, y) : return x + y

just without binding it to a name like f.

Also how do you make it return multiple arguments?

The same way like with a function. Preferably, you return a tuple:

lambda x, y: (x+y, x-y)

Or a list, or a class, or whatever.

The thing with self.entry_1.bind should be answered by Demosthenex.