What does "lambda" mean in Python, and what's the simplest way to use it?

Can you give an example and other examples that show when and when not to use Lambda? My book gives me examples, but they're confusing.

Answers


Lambda, which originated from Lambda Calculus and (AFAIK) was first implemented in Lisp, is basically an anonymous function - a function which doesn't have a name, and is used in-line, in other words you can assign an identifier to a lambda function in a single expression as such:

>>> addTwo = lambda x: x+2
>>> addTwo(2)
4

This assigns addTwo to the anonymous function, which accepts 1 argument x, and in the function body it adds 2 to x, it returns the last value of the last expression in the function body so there's no return keyword.

The code above is roughly equivalent to:

>>> def addTwo(x):
...     return x+2
... 
>>> addTwo(2)
4

Except you're not using a function definition, you're assigning an identifier to the lambda.

The best place to use them is when you don't really want to define a function with a name, possibly because that function will only be used one time and not numerous times, in which case you would be better off with a function definition.

Example of a hash tree using lambdas:

>>> mapTree = {
...     'number': lambda x: x**x,
...     'string': lambda x: x[1:]
... }
>>> otype = 'number'
>>> mapTree[otype](2)
4
>>> otype = 'string'
>>> mapTree[otype]('foo')
'oo'

In this example I don't really want to define a name to either of those functions because I'll only use them within the hash, therefore I'll use lambdas.


I do not know which book you are using, but Dive into Python has a section which I think is informative.


Use of lambda is sort of a style thing. When you can get away with a very simple function, and usually where you are just storing it somewhere (in a list of functions perhaps, or in a GUI toolkit data structure, etc.) people feel lambda reduces clutter in their code.

In Python it is only possible to make a lambda that returns a single expression, and the lambda cannot span multiple lines (unless you join the multiple lines by using the backslash-at-the-end-of-a-line trick). People have requested that Python add improvements for lambda, but it hasn't happened. As I understand it, the changes to make lambda able to write any function would significantly complicate the parsing code in Python. And, since we already have def to define a function, the gain is not considered worth the complication. So there are some cases where you might wish to use lambda where it is not possible. In that case, you can just use a def:

object1.register_callback_function(lambda x: x.foo() > 3)

def fn(x):
    if x.foo() > 3:
        x.recalibrate()
        return x.value() > 9
    elif x.bar() > 3:
        x.do_something_else()
        return x.other_value < 0
    else:
        x.whatever()
        return True

object2.register_callback_function(fn)
del(fn)

The first callback function was simple and a lambda sufficed. For the second one, it is simply not possible to use a lambda. We achieve the same effect by using def and making a function object that is bound to the name fn, and then passing fn to register_callback_function(). Then, just to show we can, we call del() on the name fn to unbind it. Now the name fn no longer is bound with any object, but register_callback_function() still has a reference to the function object so the function object lives on.


Need Your Help

Should I Use "weakSelf" In a dispatch Block?

objective-c memory-management objective-c-blocks retain-cycle

I've heard that I should always use weakSelf in blocks to avoid retain cycles, but what about dispatch blocks? In this case, my method handles an error response from my server in the following code...