Python Lambda Functions

A Python lambda function can only have one expression and no multiple lines.

It is supposed to make it easier to create some small logic in one line instead of a whole function as it is usually done.

Lambda functions are also anonymous, which means there is no need to name it.

Basic Syntax

The basic syntax is very simple, just use the lambda keyword, define the parameters needed, use ":" to separate the parameters from the expression.

The general forms is:

lambda arguments : expression

One parameter example

Look at this example using only one parameter

cubic = lambda number : number**3
print(cubic(2))
#8

Multiple parameter example

If you want, you can also have multiple parameters.

exponential = lambda multiplier, number, exponent : multiplier * number**exponent
print(exponential(2, 2, 3))
#16

Calling the Lambda Function directly

You don’t need to use a variable as we did before, you can make use of parenthesis around the lambda function and another pair of parenthesis around the arguments.

The declaration of the function and the execution will happen in the same line.

(lambda multiplier, number, exponent : multiplier * number**exponent)(2, 2, 3)
#16

Examples using lambda functions with other built-in functions

Map

The Map function applies the expression to each item in a list.

Let’s calculate the cubic of each number in the list.

numbers = [2, 5, 10]
cubics = list(map(lambda number : number**3, numbers))
print(cubics)
#[8, 125, 1000]

Filter

The Filter function will, obviously, filter the list based on the expression.

Let’s filter to have only the numbers greater than 5.

numbers = [2, 5, 10]
filtered_list = list(filter(lambda number : number > 5, numbers))
print(filtered_list)
#[10]

Watch on Youtube

You can also watch this content on Youtube: