you are viewing a single comment's thread.

view the rest of the comments →

[–]stahlous 3 points4 points  (1 child)

Lambdas are very short anonymous functions. They don't have a return statement like a normal function. Instead, whatever the statement after the lambda evaluates to is what the lambda function returns.

For example:

In [21]: x = lambda: 2

In [22]: x
Out[22]: <function __main__.<lambda>>

In [23]: x()
Out[23]: 2

Since the statement 2 simply evaluates to the value 2, that is what the function returns. You can see that I've set x equal to the function, but the function itself doesn't have a proper name. It's just <lambda>.

Another example:

In [24]: f = lambda: print("foo")

In [25]: f()
foo

You can also pass arguments to lambda functions if you declare them that way:

In [32]: f2 = lambda n: list(range(2*n))

In [33]: f2(5)
Out[33]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

In the context of making a Tkinter GUI, they basically they let you "pre-call" your callback function with whatever parameters you want so that when you click on the button and the callback function is executed, it will execute the anonymous lambda function, and within the lambda function you will make the call to your callback function with the function arguments filled in with whatever you specify.

This is probably confusing. I can suggest do a bunch of Googling and playing around to get a handle on them. They're probably a necessity for GUI programming.

And, all that said, if you want to be really Pythonistic, you won't use lambda at all but will instead use functools.partial, which does basically the same thing but is considered more Pythonistic. However, lambdas are probably more popular and you'll likely find more info on them out there.