Member-only story
Understand Python Lambdas in 3 Minutes
Lambda expressions are also known as anonymous functions. Learn how and when to use them

In Python, a lambda function is an anonymous function (a function without a name) that can take any number of arguments but only contains a single expression. As an example, here is a lambda that multiplies a number by three:
lambda x : x * 3
This lambda isn’t particularly useful as-is because now there’s no way to call it. However, you can assign it to a variable and then call it like a regular function:
mult3 = lambda x : x * 3
mult3(15.0) # returns 45
You don’t need to assign a lambda to a variable. Instead, you can call it right away like this:
(lambda x : x * 3)(15.0) # returns 45.0
Lambda functions are especially useful when the functionality is needed for only a short period of time and you don’t want to waste resources by creating a separate method to do the job.
How To Use Lambdas
You already saw some basic examples of lambdas, but let’s take a closer look at how they work.
Syntax
This is the basic syntax of a lambda expression:
lambda arguments : expression
For example, you can create a lambda that squares a number:
pow2 = lambda x: x * x
pow2(5.0) # returns 25.0
As another example, here is a lambda expression that takes more than one argument:
sum = lambda a, b : a + b
sum(4.0, 5.0) # returns 9.0
Tip: Lambdas are not useful when used this way. If you want to assign a lambda to a variable, just create a normal function with def
.
How is a lambda an anonymous function?
Lambdas are also known as anonymous functions. To demonstrate why, let’s jump back to the example of squaring a number. This time, let’s not assign the lambda to a variable but call it directly instead:
(lambda x : x * x)(15.0) # returns 225.0