{article Dive into Python}{title} {text}{/article}

Small anonymous functions can be created with the lambda keyword. This function returns the sum of its two arguments: lambda a, b: a+b. Lambda functions can be used wherever function objects are required. They are syntactically restricted to a single expression. Semantically, they are just syntactic sugar for a normal function definition. Like nested function definitions, lambda functions can reference variables from the containing scope:

lambda is just an in−line function

>>> def f(x):
return x*2

>>> f(3)
6
>>> g = lambda x: x*2
>>> g(3)
6
>>> (lambda x: x*2)(3)
6
>>>

This is a lambda function that accomplishes the same thing as the normal function above it. Note the
abbreviated syntax here: there are no parentheses around the argument list, and the return keyword is
missing (it is implied, since the entire function can only be one expression). Also, the function has no name, but
it can be called through the variable it is assigned to.


You can use a lambda function without even assigning it to a variable. This may not be the most useful thing
in the world, but it just goes to show that a lambda is just an in−line function.

Function objects returned by running lambda expressions work exactly the same as those created and assigned by defs, but there are a few differences that make lambdas useful in specialized roles:

Apart from those distinctions, defs and lambdas do the same sort of work. For instance, we’ve seen how to make a function with a def statement: