Anonymous Functions and lambda
Python allows one to create anonymous functions using the lambda keyword. They are “anonymous” because they are not declared in the standard manner, i.e., using the def statement. (Unless assigned to a local variable, such objects do not create a name in any namespace either.) However, as functions, they may also have arguments. An entire lambda “statement” represents an expression, and the body of the lambda expression must also be given on the same line as the declaration. We now present the syntax for anonymous functions using lambda:
lambda [arg1[, arg2, … argN]]: expression
Arguments are optional, and if used, are usually part of the expression as well. Calling lambda with an appropriate expression yields a function object which can be used like any other function. They can be passed to other functions, aliased with additional references, be members of container objects, and as callable objects, be invoked (with any arguments, if necessary). When called, these objects will yield a result equivalent to the same expression if given the same arguments. They are indistinguishable from functions which return the evaluation of an equivalent expression.
Before we look at any examples using lambda, we would like to review single-line statements and then show the resemblances to lambda expressions.
def true(): return 1
The above function takes no arguments and always returns 1. Single line functions in Python may be written on the same line as the header. Given that, we can rewrite our true() function so that it looks something like the following.
def true(): return 1
We will present the named functions in this manner for the duration of this topics because it helps one visualize their lambda equivalents. For our true() function, the equivalent lambda expression (no arguments, returns 1) is:
Usage of the named true() function is fairly obvious, but not for lambda. Do we just use it as is, or do we need to assign somewhere? A lambda function by itself serves no purpose, as we see here:
>>> lambda: 1 <function <lambda> at 0x020F1C70>
In the above example, we simply created a lambda function, but did not save it anywhere nor did we call it. The reference count for this function object is set to 1 on creation of the function object, but because no reference is saved, goes back down to zero and garbagecollected.
To keep the object around, we can save it into a variable and invoke it any time after. Perhaps now is a good opportunity:
>>> true = lambda :1 >>> true() 1
Assigning it looks much more useful here. Likewise, we can assign lambda expressions to a data structure such as a list or tuple where, based on some input criteria, we can choose which function to execute as well as what the arguments would be. (In the next section, we will show how to use lambda expressions with functional programming constructs.)
Let us now design a function that takes two numeric or string arguments and returns the sum for numbers or the concatenated string. We will show the standard function first, followed by its unnamed equivalent.
def add(x, y): return x + y? lambda x, y: x + y
Default and variable arguments are permitted as well, as indicated in the following examples:
def usuallyAdd2(x, y=2): return x+y ? lambda x, y=2: x+y def showAllAsTuple(*z): return z ? lambda *z: z
Seeing is one thing, so we will now try to make you believe by showing how you can try them in the interpreter:
>>> a = lambda x, y=2: x + y >>> a(3) 5 >>> a(3,5) 8 >>> a(0) 2 >>> a(0,9) 9 >>> >>> b = lambda *z: z >>> b(23, 'zyx') (23, 'zyx') >>> b(42) (42,)
One final word on lambda. Although it appears that lambda’s are a one-line version of a function, they are not equivalent to “inline” statements in C++, whose purpose is bypassing function stack allocation during invocation for performance reasons. A lambda expression works just like a function, creating a frame object when called.