Lambda Functions

Learn about the usage of lambda functions in Python.

We'll cover the following

Lambda functions

Normal functions have names. They are defined using the def keyword. Lambda functions do not have names. They are defined using the lambda keyword and are built at execution time.

Lambda functions are commonly used for short functions that are convenient to define at the point where they are called. They are also called anonymous functions or inline functions.

A lambda function can take any number of arguments but can return only one value. Its syntax is:

lambda arguments : expression

The : separates the parameters to be passed to the lambda function and the function body. The result of running the function body is returned implicitly.

Here are a few examples of lambda functions:

# function that receives an argument and returns its cube 
lambda n : n * n * n

# function that receives 3 arguments and returns average of them
lambda x, y, z : (x + y + z) / 3

# function that receives a string, strips any whitespace and returns
# the uppercase version of the string
lambda s : s.trim( ).upper( )

Lambda functions are often used as an argument to other functions. For example, the lambdas above can be passed to the print() function to print the value that they return, as shown below:

Get hands-on with 1200+ tech skills courses.