Lambda functions

Lambda functions are a very popular programming concept that is especially profound in functional programming. In other programming languages, lambda function are sometimes known as anonymous functions, lambda expressions, or function literals. Lambda functions are anonymous functions that don't have to be bound to any identifier (variable).

Lambda functions in Python can be defined only using expressions. The syntax for lambda functions is as follows:

lambda <arguments>: <expression>

The best way to present the syntax of lambda functions is through comparing a "normal" function definition with its anonymous counterpart. The following is a simple function that returns the area of a circle of a given radius:

import math


def circle_area(radius):
return math.pi * radius ** 2

 The same function expressed as a lambda function would take the following form:

lambda radius: math.pi * radius ** 2

Lambda in functions are anonymous, but it doesn't mean they cannot be referred to by any identifier. Functions in Python are first-class objects, so whenever you use a function name, you're actually using a variable that is a reference to the function object. As with any other function, lambda functions are first-class citizens, so they can also be assigned to a new variable. Once assigned to a variable, they are seemingly undistinguishable from other functions, except for some metadata attributes. The following transcripts from interactive interpreter sessions illustrates this:

>>> import math
>>> def circle_area(radius):
... return math.pi * radius ** 2
...
>>> circle_area(42)
5541.769440932395
>>> circle_area
<function circle_area at 0x10ea39048>
>>> circle_area.class
<class 'function'>
>>> circle_area.name
'circle_area'

>>> circle_area = lambda radius: math.pi * radius ** 2
>>> circle_area(42)
5541.769440932395
>>> circle_area
<function <lambda> at 0x10ea39488>
>>> circle_area.__class__
<class 'function'>
>>> circle_area.__name__
'<lambda>'

Let's take a look at the map(), filter(), and reduce() functions in the next sections.