How to Use the Python lambda Function

09/07/2021

Contents

In this article, you will learn how to use the Python lambda function.

Python lambda Function

The lambda function in Python is a small anonymous function that can take any number of arguments, but can only have one expression.

Syntax

The syntax for a lambda function is:

lambda arguments : expression
Examples
Example1

Here’s an example usage of the lambda function:

>>> add = lambda x, y : x + y
>>> add(2, 3)
5

In this example, lambda is defining an anonymous function (add) that takes two arguments (x and y) and returns their sum (x + y).

Example2

And lambda functions are often used in conjunction with higher-order functions, such as map, filter, and reduce, which take one or more functions as arguments and use them to process data.

Here’s an example using map:

>>> numbers = [1, 2, 3, 4, 5]
>>> squared = list(map(lambda x: x**2, numbers))
>>> print(squared)
[1, 4, 9, 16, 25]

In this example, map takes two arguments: a lambda function and an iterable (numbers). The lambda function takes one argument (x) and returns its square (x**2). map applies this function to each element of the iterable, and the resulting list of squared values is stored in the variable squared.

Example3

The filter() function is used to filter out elements from an iterable based on some condition. Here’s an example:

>>> numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> evens = list(filter(lambda x: x % 2 == 0, numbers))
>>> print(evens)
[2, 4, 6, 8, 10]

In this example, the filter() function takes two arguments: a lambda function and an iterable (numbers). The lambda function takes one argument (x) and returns True if x is even (x % 2 == 0), and False otherwise. filter applies this function to each element of the iterable and returns only the elements for which the function returns True.

Example4

Finally, the reduce() function is used to perform some operation on a list and reduce it to a single value. Here’s an example:

>>> from functools import reduce
>>> numbers = [1, 2, 3, 4, 5]
>>> product = reduce(lambda x, y: x * y, numbers)
>>> print(product)
120

In this example, reduce takes two arguments: a lambda function and an iterable (numbers). The lambda function takes two arguments (x and y) and returns their product (x * y). reduce applies this function cumulatively to the elements of the iterable, and the final result is stored in the variable product.