How to Use Lambda Functions in Python?

In this tutorial, I will explain how to use lambda functions in Python. During a project, our team discussed lambda functions and their usage, then I explored more about this topic. I will cover what lambda functions are, their syntax, and common use cases, and walk through several practical examples and screenshots.

Use Lambda Functions in Python

Lambda functions, also known as anonymous functions, are functions that are defined without a name using the lambda keyword. Unlike regular functions defined with def, lambda functions are meant to be small, one-line functions used for a short period. Their nameless, throwaway nature makes them very useful for functional programming.

The syntax for lambda functions is:

lambda arguments : expression 

Lambda functions can take any number of arguments but can only contain a single expression. They return the value of that expression implicitly, without needing a return statement.

For example, here’s a lambda function that takes a number x and returns its square:

square = lambda x : x ** 2
print(square(5)) 

Output:

25

You can see the output in the screenshot below.

Use Lambda Functions in Python

Read How to Use the Python pop() Function?

Common Use Cases for Lambdas in Python

Let’s look at some of the most common scenarios where lambda functions come in handy with real-world examples.

1. Sort Lists

Say you have a list of names and want to sort them by last name. You can use a lambda with the sort() method:

names = ["John Smith", "Jane Doe", "Bob Johnson", "Alice Williams"] 
names.sort(key=lambda name: name.split()[-1])
print(names) 

Output:

['Jane Doe', 'Bob Johnson', 'John Smith', 'Alice Williams']

You can see the output in the screenshot below.

How to Use Lambda Functions in Python

The lambda takes each name, splits it on whitespace, and returns the last element (the last name) to use as the sorting key.

Check out How to Use wait() Function in Python?

2. Filter Lists

Lambda functions are often used with filter() to concisely filter lists based on a condition. For example, to filter a list of US city populations to only those above 1 million:

populations = [
    ("New York City", 8804190),
    ("Los Angeles", 3898747), 
    ("Chicago", 2746388),
    ("Houston", 2304580)
]

big_cities = list(filter(lambda city: city[1] > 1000000, populations))
print(big_cities)   

Output:

[('New York City', 8804190), ('Los Angeles', 3898747), ('Chicago', 2746388), ('Houston', 2304580)]

You can see the output in the screenshot below.

Use Lambda Functions in Python filter lists

The lambda returns True if the city’s population (the second element of the tuple) is greater than 1 million, filtering the list.

Read How to Use the randint() Function in Python?

3. Map Values

The map() function applies a function to every element in an iterable. It’s commonly used with lambdas for simple data transformations.

For instance, to convert temperatures from Fahrenheit to Celsius:

fahrenheit = [90, 72, 81, 63]
celsius = list(map(lambda temp: round((temp - 32) * 5/9, 1), fahrenheit))
print(celsius)

Output:

[32.2, 22.2, 27.2, 17.2]

You can see the output in the screenshot below.

Use Lambda Functions in Python Map Values

The lambda applies the temperature unit conversion formula to each value in the Fahrenheit list.

Read How to Use the find() Function in Python?

4. Reduce Values

The reduce() function (from the functools module) performs a rolling calculation on a list, accumulating the result into a single return value. It’s often used with lambdas to concisely define the accumulation operation.

For example, to calculate the product of a list of integers:

from functools import reduce

numbers = [3, 5, 2, 4] 
product = reduce(lambda x, y: x * y, numbers)
print(product)  # Output: 120

The lambda multiplies the accumulated value x with the next element y, reducing the list to a single product.

Check out How to Use the map() Function in Python?

Limitations of Lambda Functions

While lambdas are powerful, they do have some constraints to be aware of:

  • Lambdas can only contain a single expression – no statements like if/else or for/while loops are allowed. If your function is complex, stick with def.
  • Lambdas don’t have a name, which can make error messages less helpful when debugging. Using descriptive variable names can help.
  • Overusing lambdas, especially with complicated expressions, can make your code harder to read. Use them judiciously and opt for regular functions if clarity is compromised.

Read How to Implement and Use the hash() Functions in Python?

Conclusion

In this tutorial, I have explained how to use lambda functions in Python. I discussed some common use cases for lambdas such as sorting lists, filter lists, map values, and reduce values. I also covered see limitations of lambda functions.

You may also read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.