Lambda

A lambda function is anonymous function which returns a single expression.

It can take any number of arguments.

Basic Lambda Example

Let's look at the following example:

Output:

The lambda function accepts three arguments - a, b, c and returns the result of the expression - a + b + c.

In this case the calculation of the lambda function is: 2 + 3 + 4 = 9.

The lambda function in this example is equivalent to:

Lambda inside function

A lambda function can be assigned to a variable and used inside a function.

Let's look at the following example:

get_calculation_function returns a function which is assigned to the multiplication variable.

Because of the passed argument - 3, the function expression turns from this:
lambda n : n * 2 + base_num to this:
lambda n : n * 2 + 3

When multiplication is called with argument 4 the following calculations are made:

n = 4

n : n * 2 + 3

4 * 2 + 3 = 11

Use case

A common use case for the lambda function is in list iterating functions such as map.

Example:

Output:

There are many such functions which will be explained in another lesson.