What Is a Lambda Function in Python [Simple Code Examples]

If you are getting started with Python, understanding what a lambda is can be a bit confusing. Let’s clarify a few things straight away.

A lambda function is also called an anonymous function because a lambda is a function without a name. To define a lambda in Python you use the keyword lambda followed by one or more arguments, a colon (:), and a single expression.

We will start with a simple example of a lambda function to get used to its syntax and then we will look at how you can use a lambda function in different scenarios.

To practice all the examples we will use the Python interactive shell so make sure to open it so you can follow along.

Lambda Function Syntax in Python

Let’s start by explaining the syntax of a lambda function.

A lambda function starts with the lambda keyword followed by a list of comma-separated arguments. The next element is a colon (:) followed by a single expression.

lambda <argument(s)> : <expression>

As you can see a lambda function can be defined in a single line.

Below you can see a very simple lambda that multiplies the number x (argument) by 2:

lambda x : 2*x

Here’s what happens if you define this lambda in the Python shell, try it out:

>>> lambda x : 2*x
<function <lambda> at 0x101451cb0>

You get back a function object. Also, interestingly when defining a lambda you don’t need a return statement as part of the expression.

If you add a return statement to the expression, you receive a syntax error.

>>> lambda x : return 2*x
  File "<stdin>", line 1
    lambda x : return 2*x
                    ^
SyntaxError: invalid syntax

There is no need to include a return statement when defining a lambda function in Python.

How to Use a Lambda Function in Python

We have seen how to define a lambda, but how can we call it?

Start by calling the lambda function without assigning the function object to a variable. You can achieve this by using parentheses as shown below:

(lambda x : 2*x)(2)

Surround the lambda expression with parentheses followed by parentheses surrounding the arguments you want to pass to the lambda.

This is the output of the lambda call:

>>> (lambda x : 2*x)(2)
4

Nice!

You also have another option. You can assign the function object returned by the lambda function to a variable, and then call the function using the variable name.

>>> multiply = lambda x : 2*x
>>> multiply(2)
4

I feel this goes against the idea of not giving a name to a lambda, but it is worth knowing.

Before continuing to read this article make sure you try out all the examples we have seen so far on your computer. This will help you get familiar with lambdas before writing more complex examples of code.

I still remember the first time I started reading about lambdas, I was a bit confused. So don’t worry if you feel the same right now 🙂

Passing Multiple Arguments to a Lambda Function

In the previous sections, we have seen how to define and execute a lambda function.

We have also mentioned that a lambda can have one or more arguments, let’s see an example with two arguments.

Create a lambda that multiplies the arguments x and y:

lambda x, y :  x*y

As you can see, the two arguments are separated by a comma.

>>> (lambda x, y :  x*y)(2,3)
6

The output returns the correct number (2*3).

A lambda is an IIFE (Immediately Invoked Function Expression). It’s a way to say that a lambda function is executed immediately as soon as it’s defined.

Difference Between a Lambda Function and a Regular Function

Before continuing to look at how you can use lambdas in your Python programs, it’s important to see how a regular Python function and a lambda compare to each other.

Take the previous example:

lambda x, y :  x*y

You can also write this expression as a regular function using the def keyword:

def multiply(x, y):
    return x*y

You will notice immediately three differences compared to the lambda form:

  1. When using the def keyword you have to specify a name for the function.
  2. Parentheses surround the two arguments.
  3. You return the result of the function using the return statement.

As mentioned previously, assigning a lambda function to a variable is optional:

multiply_lambda = lambda x, y :  x*y

Let’s compare the objects for these two functions:

>>> def multiply(x, y):
...     return x*y
... 
>>> multiply
<function multiply at 0x100af4700>
>>> 
>>> multiply_lambda = lambda x, y :  x*y
>>> multiply_lambda
<function <lambda> at 0x100af45e0>

Here we can see a difference: the function defined using the def keyword is identified by the name “multiply” while the lambda function is identified by a generic <lambda> label.

And let’s see what the type() built-in function returns when applied to both functions:

>>> type(multiply)
<class 'function'>
>>> type(multiply_lambda)
<class 'function'>

The type of both functions is the same.

Can You Use If-Else in a Python Lambda?

Let’s find out if you can use an if-else statement in a lambda function.

lambda x: x if x > 2 else 2*x

This lambda should return x if x is greater than 2 otherwise it should return x multiplied by 2.

Firstly, let’s confirm if its syntax is correct:

>>> lambda x: x if x > 2 else 2*x
<function <lambda> at 0x101451dd0>

No errors so far, let’s test the function by calling it:

>>> (lambda x: x if x > 2 else 2*x)(1)
2
>>> (lambda x: x if x > 2 else 2*x)(2)
4
>>> (lambda x: x if x > 2 else 2*x)(3)
3

The if-else logic in the lambda is working well.

You can also see that the code can become more difficult to read if you make the lambda expression too complex.

As mentioned at the beginning of this tutorial: a lambda function can only have a single expression. This makes it applicable to a limited number of use cases compared to a regular function.

Also, remember that you cannot have multiple statements in a lambda expression.

Error Handling For Python Lambdas

In the section in which we have looked at the difference between lambdas and regular functions, we have seen the following:

>>> multiply
<function multiply at 0x101451d40>
>>> multiply_lambda
<function <lambda> at 0x1014227a0>

Where multiply was a regular function and multiply_lambda was a lambda function.

As you can see the function object for a regular function is identified with a name, while the lambda function object is identified by a generic <lambda> name.

This also makes error handling a bit more tricky with lambda functions because Python tracebacks don’t include the name of the function in which an error occurs.

Let’s create a regular function and pass to it arguments that cause the Python interpreter to raise an exception:

def calculate_sum(x, y):
    return x+y

print(calculate_sum(5, 'Not_a_number'))

When you run this code in the Python shell you get the following error:

>>> def calculate_sum(x, y):
...     return x+y
... 
>>> print(calculate_sum(5, 'Not_a_number'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in calculate_sum
TypeError: unsupported operand type(s) for +: 'int' and 'str'

From the traceback, you can see that the error occurs at line 2 of the calculate_sum() function.

Now, replace this regular function with a lambda function that implements the same logic:

calculate_sum = lambda x, y: x+y
print(calculate_sum(5, 'Not_a_number'))

This time the output is:

>>> calculate_sum = lambda x,y: x+y
>>> print(calculate_sum(5, 'Not_a_number'))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <lambda>
TypeError: unsupported operand type(s) for +: 'int' and 'str'

The type of exception and the error message are the same, but this time the traceback tells us that there was an error at line 1 of the function <lambda>.

Not very useful if you have several lambda functions in your code.

This is a reason for using regular functions instead of lambda functions.

Passing a Variable List of Arguments to a Python Lambda

In this section, we will see how to pass a variable list of arguments to a Python lambda.

To pass a variable number of arguments to a lambda you can use *args the same way you do with a regular function.

Here is an example:

(lambda *args: max(args))(5, 3, 4, 10, 24)

When you execute this code you get back the maximum between the arguments you pass to the lambda:

>>> (lambda *args: max(args))(5, 3, 4, 10, 24)
24

You don’t necessarily have to use the keyword args. What’s important is the * before args that in Python represents a variable number of arguments.

Let’s confirm that’s the case by replacing args with the variable numbers:

>>> (lambda *numbers: max(numbers))(5, 3, 4, 10, 24)
24

It still works fine!

More Examples of Using Lambda Functions

Before completing this tutorial let’s have a look at a few more examples of lambdas.

These examples can give you more ideas on how to use lambdas in your Python programs.

Calculate the area of a rectangle with a lambda

>>> area = lambda length, width: length * width
>>> area(5, 4)
20

Reverse a string using slicing and a lambda

>>> reverse_string = lambda s: s[::-1]
>>> reverse_string("hello")
'olleh'

Check if a number is within a given range using a lambda

>>> in_range = lambda x, low, high: low <= x <= high
>>> in_range(5, 1, 10)
True
>>> in_range(15, 1, 10) 
False

Conclusion

In this tutorial, we have covered:

  • What a Python lambda function is.
  • How to define a lambda.
  • How to execute a lambda.

We went through examples of lambdas with one or more arguments and we have also seen how a lambda returns a function object (without the need for a return statement).

Now you know that an alternative name for a lambda is an anonymous function because when you define it you don’t bind it to a name.

Also, analyzing the difference between regular functions and lambda functions in Python has helped us understand how a lambda works.

It’s very common to use lambda functions when you need them only once in your code. If you need a function that gets called multiple times in your codebase, using regular functions is a better approach to avoid code duplication.

Always remember how important is to write clean code. Code that anyone can quickly understand and maintain.

Now you have a choice between lambdas and regular functions, make the right one! 🙂

Related article: now that you know the basics of lambda functions, have a look at one of the applications of Python lambdas: sorting lists of dictionaries.

Leave a Comment