Track
Python Lambda Functions: A Beginner’s Guide
Lambda functions in Python are powerful, concise tools for creating small, anonymous functions on the fly. They are perfect for simplifying short-term tasks, streamlining code with higher-order functions like map
, filter
, or sorted
, and reducing clutter when defining temporary or throwaway logic. They also offer an elegant solution for improving code readability in simple scenarios. This article will explore what lambda functions are, their characteristics, and how to use them effectively.
In this guide, we’ll provide a complete guide to lambda functions in Python, covering their mechanics, syntax, and how they compare to standard functions, with simple examples to illustrate key concepts.We explore common use cases, such as using lambda functions within functional programming paradigms and their efficiency relative to standard functions.. Practical examples and best practices are included to help you effectively incorporate lambda functions into your Python programming.
What is a Lambda Function in Python?
Lambda functions differ from standard Python functions in several key ways. They are anonymous expressions, meaning they have no name unless explicitly assigned to a variable. They are also more concise and defined in a single line without the need for a return
statement. This makes them ideal for simple, one-time operations and for use as inline arguments in higher-order functions like map
, filter
, and sorted
.
Here is an example of a lambda function that adds two numbers:
lambda x, y: x + y
<function __main__.<lambda>(x, y)>
How lambda functions work
How does this lambda function work? To understand it, let's compare it to a standard Python function.
# Example: add two numbers using standard Python function
def add_numbers(x, y):
return x + y
This standard function is straightforward. The def
keyword defines the function, which takes two arguments, x
and y
. It calculates the sum of x
and y
and returns the result.
Now, let’s see how our lambda function achieves the same task.
# Example: add two numbers using a lambda function
lambda x, y: x + y
<function __main__.<lambda>(x, y)>
The lambda
keyword signifies that we are defining a lambda function, eliminating the need for the def
keyword. Following this lambda
keyword, the input arguments x
and y
are listed. After the colon, we specify the expression whose result will be returned, x + y
.
Writing Lambda Functions in Python: Examples
To help you get to grips with the concepts we’ve explored so far, let’s look at a few examples of how Lambda functions work in Python.
Step-by-step guide to writing lambda functions
Lambda functions are ideal for creating short, straightforward functions without extra complexity.
For example, suppose you want to check if a given non-zero integer is even. You could write a standard Python function, but the same functionality can be achieved with a concise one-liner lambda function assigned to a variable: is_even = lambda x: x % 2 == 0
.
Here, the lambda function on the right side of the assignment takes an input x
and returns True
if x
is even (that is if the remainder when divided by 2 is 0).
This lambda function is then assigned to the variable is_even
, allowing it to be called like a regular function. For instance, is_even(5)
(returns False
) and is_even(678432)
(returns True
).
Lambda functions are also great for defining simple formulas. For instance, to convert Celsius to Fahrenheit, you could use a lambda function: c_to_f = lambda c: (c * 9/5) + 32
. You then call the function like any other function: c_to_f(0)
.
Common use cases for lambda functions
Lambda functions are often used in functional programming, particularly with functions like map()
and filter()
, which take other functions as arguments to process elements in a collection. Let's see how to use a lambda function with filter()
. Here's a code snippet:
# Use filter with lambda function
numbers = [1, 2, 3, 4, 5, 6, 7, 8]
evens = filter(lambda x: x % 2 == 0, numbers)
print(list(evens)) # print the list of the filter object to see the result
[2, 4, 6, 8]
In this code, we start by defining a set of numbers
. Next, we create a lambda function to check if a number is even. The filter
function applies this lambda function to the numbers
set. We then print the list of even numbers identified by the filter
function.
Similarly, we can use the map
function to apply a lambda to a collection of elements. In the example below, we calculate the lengths of strings in a list by mapping the len()
function to each element.
# Use map with lambda function
fruits = ['apple', 'banana', 'cherry']
lengths = list(map(lambda x: len(x), fruits))
print(lengths)
[5, 6, 6]
Lambda function are also used with the sorted()
function, which sorts the elements of a collection to return a new collection. In the following example (without a lambda), we use the sorted()
function to sort a list of numbers.
numbers = [1, 10, -1, 3, -10, 5]
sorted_stuff = sorted(numbers)
print(sorted_stuff)
[-10, -1, 1, 3, 5, 10]
Suppose we wanted to sort the list of numbers by absolute value. How would we achieve this? The sorted()
function includes a key
argument that allows us to customize the sorting order by providing a lambda function.
# Sort according to absolute value
sorted_numbers_absolute = sorted(numbers, key=lambda x: abs(x))
print(sorted_numbers_absolute)
[1, -1, 3, 5, 10, -10]
Another use case for sort()
with a lambda
function is to sort a list of tuples based on a specific element, say the second one.
# Sort a list of tuples by the second element
data = [(1, 3), (2, 1), (4, 2)]
sorted_data = sorted(data, key=lambda x: x[1])
print(sorted_data)
[(2, 1), (4, 2), (1, 3)]
In this code snippet, we define data
as a list of tuples. We then use the sorted()
function with the key
parameter, where a lambda function extracts the second element of each tuple for sorting.
Are Lambda Functions Faster in Python?
In Python, lambda functions are not inherently faster than standard functions, as both are compiled to similar bytecode. However, they can slightly reduce overhead in cases where defining a full function would add unnecessary boilerplate.
Here are a few test cases comparing lambda functions to standard Python functions. The code was executed on my laptop, a MacBook Pro with an Apple M1 Pro chip, 16 GB of memory, running macOS Sequoia 15.2.
Lambda functions can be used inline as anonymous functions when passed directly to higher-order functions like map()
, filter()
, or sorted()
. This avoids the need to define and reference a separate named function, reducing both boilerplate code and lookup overhead.
import time
numbers = list(range(1, 1000000))
# Standard function
def double_standard(x):
return x * 2
start = time.time()
map(double_standard, numbers)
print(time.time() - start)
# Lambda function
double_lambda = map(lambda x: x * 2, numbers)
start = time.time()
list(map(lambda x: x * 2, numbers))
print(time.time() - start)
3.504753112792969e-05
2.384185791015625e-05
Lambda functions are ideal for one-time or temporary use, as they eliminate the need for a formal def
block, saving both time and space. In the following code block, we compare the performance of a standard function to that of a lambda function. We sort a dictionary with a million elements, where the keys are random two-letter codes, and the values are random integers.
import random
import string
# Generate a dictionary with elements of the form 'XX': number.
NUMBER_ITEMS = 1000000
items = {
''.join(random.choices(string.ascii_uppercase, k=2)): random.randint(1, 100)
for _ in range(NUMBER_ITEMS)
}
# Standard function (extra definition step)
def sort_standard(item):
return item[1]
print('Standard')
start = time.time()
sorted_items_standard = sorted(items, key=sort_standard)
print(time.time() - start)
print(sorted_items_standard[:5])
print()
# Lambda function
print('Lambda')
start = time.time()
sorted_items_lambda = sorted(items, key=lambda x: x[1])
print(time.time() - start)
print(sorted_items_lambda[:5])
print()
Standard
0.00011610984802246094
['OA', 'VA', 'XA', 'IA', 'BA']
Lambda
0.00011014938354492188
['OA', 'VA', 'XA', 'IA', 'BA']
Python Lambda Functions: Examples and Practice
Let’s work through some more practical examples to showcase how Lambda functions work in Python.
Practical examples
Lambda functions are often used with built-in Python methods. For instance, let's look at using reduce()
to apply a user-defined binary function cumulatively to the items of a sequence.
# Example: Use lambda function with built-in Python method reduce.
from functools import reduce
numbers = [5, -6, 2, 7]
total = reduce(lambda x, y: x + y, numbers)
print(f'The sum of the numbers is {total}.')
The sum of the numbers is 8.
Similar to filter()
or map()
above, reduce()
applies a function, here given by a lambda, to a set of elements.
Now, let’s explore another built-in Python function, zip()
. The zip
function pairs corresponding elements from multiple lists into tuples. For example, the result of zip(['a', 'b', 'c'], [1, 2, 3])
is [('a', 1), ('b', 2), ('c', 3)]
.
# Example: Use lambda function with built-in Python method zip.
list1 = [1, 2, 3]
list2 = [4, 5, 6]
# Using zip and a lambda function to multiply corresponding elements
result = list(map(lambda x: x[0] * x[1], zip(list1, list2)))
print(f'The result of multiplying corresponding elements is {result}.')
The result of multiplying corresponding elements is [4, 10, 18].
This code calculates the product of corresponding elements from two lists, list1
and list2
. It uses zip()
to pair elements from the lists into tuples, then applies a lambda function with map()
to multiply the paired elements, and finally converts the result into a list.
Real-world example: data transformation
Let’s imagine you run a fruit stand and want to compute the total sales amount for each type of fruit.
First, let's create some sales records.
# Sample data: list of dictionaries representing sales records
sales_data = [
{'fruit': 'peaches', 'price': 1.41, 'quantity': 3},
{'fruit': 'pears', 'price': 1.21, 'quantity': 2},
{'fruit': 'mangoes', 'price': 0.56, 'quantity': 3},
]
Now, we use map()
with a lambda function to compute total_sales
by multiplying the price and quantity for each item in the sales_data
dictionary. The **record
syntax unpacks the original dictionary, ensuring that all its keys and values are preserved in the new dictionary.
# Using a lambda function to calculate total sales for each record
transformed_data = list(
map(
lambda entry: {**entry, 'total_sales': round(entry['price'] * entry['quantity'], 2)},
sales_data
)
)
Finally, we print out each record of the transformed data.
# Print the transformed data
for record in transformed_data:
print(record)
{'fruit': 'peaches', 'price': 1.41, 'quantity': 3, 'total_sales': 4.23}
{'fruit': 'pears', 'price': 1.21, 'quantity': 2, 'total_sales': 2.42}
{'fruit': 'mangoes', 'price': 0.56, 'quantity': 3, 'total_sales': 1.68}
Simple problems for users to solve with lambda functions
If you'd like to practice using lambda functions, here are some problems to try.
- Given a number, find its square.
- Given two numbers, find the larger one.
- Given a number, check if it is odd.
- Given a list of positive integers, filter out all the odd numbers.
- Sort a list of 3-element tuples using their third elements.
- Extract the domain from an email address. For example, given
user@example.com
, extractexample.com
.
Common lambda-related mistakes
Let's look at some common mistakes programmers make with lambdas and some fixes.
1. The first mistake is to use a lambda function when it's inappropriate. It’s important to remember that lambda functions are designed for short, simple tasks, not for handling complex logic. For example, the following code snippet is not an ideal use case for a lambda function.
# Complex logic in a lambda
result = lambda x: (x ** 2 + x - 1) / (x + 1 if x != -1 else 1)
print(result(5)) # Hard to understand
4.833333333333333
In this case, it's better to just use a standard Python function.
def complex_logic(x):
if x == -1:
return x ** 2 + x - 1
return (x ** 2 + x - 1) / (x + 1)
print(complex_logic(5))
4.833333333333333
2. Another simple mistake to make is to muddle up the syntax. For instance, forgetting the keyword lambda
will result in an error. Another common syntax mistake is to leave out the input argument(s):
# Forgetting the required arguments
numbers = [1, 2, 3, 4]
squared = map(lambda: x ** 2, numbers) # <-- Where is the input argument? Error: lambda missing argument
The fix is to include the input argument:
squared = map(lambda x: x ** 2, numbers)
A good way to catch mistakes like this is to include informal, simple test cases when developing.
print(list(squared))
[1, 4, 9, 16]
3. Another mistake to watch out for is not including logic for edge cases. For instance, this code fails when y
is 0.
# Dividing without handling zero
divide = lambda x, y: x / y
The fix is to include a simple if
statement to catch the offending case or to wrap the code in an exception block.
safe_divide = lambda x, y: x / y if y != 0 else "undefined"
print(safe_divide(5, 0))
undefined
4. A more subtle problem is to forget to convert the iterator to a list when outputting the results. For instance, the map()
function returns a map
object, not a list.
# Forgetting to convert to a list
numbers = [1, 2, 3]
squared = map(lambda x: x ** 2, numbers)
print(squared) # <-- squared is the map, not the result
<map object at 0x1084bf610>
To access the results, convert the map
object to a list
.
print(list(squared)) # list(squared) gives the result
[1, 4, 9]
Python Lambda Debugging Strategies
So, how do we go about debugging lambdas? Here are some possibilities.
- Break down the lambda. Temporarily convert it to a named function for debugging purposes.
- Use print statements to display intermediate values in higher-order functions such as
map()
orfilter()
. - Test edge cases. Test with extreme, invalid, or boundary values to catch potential errors.
A useful trick for printing intermediate steps is to include a print
statement inside a tuple alongside the result. The desired output can then be passed to the higher-order function by indexing the tuple at position 1.
Here’s an example:
numbers = [1, 2, 3, 4, 5]
# Lambda function with print to debug intermediate values
filtered_numbers = filter(lambda x: (print(f'Checking: {x} -> {x >= 3}'), x >= 3)[1], numbers)
# Converting filter object to list to force evaluation
print(list(filtered_numbers))
Checking: 1 -> False
Checking: 2 -> False
Checking: 3 -> True
Checking: 4 -> True
Checking: 5 -> True
[3, 4, 5]
In this code, a trick is used to print intermediate steps while filtering a list of numbers. The lambda function in filter
includes a tuple: the first element is a print
statement that logs the current number and whether it satisfies the condition (x >= 3
), and the second element is the condition itself.
The [1]
at the end of the lambda ensures that the condition (x >= 3
) is returned to the filter
function while allowing the print
statement to execute for debugging.
Converting the filter
object to a list forces the evaluation of all elements, triggering the print
statements for each number. This approach helps debug the logic while maintaining the functionality of the filtering operation.
Best Practices for Using Lambda Functions
Best practices for using lambda functions involve understanding when they are appropriate and when they should be avoided.
When to use Lambda functions
- Short, simple logic. Ideal for concise operations that don’t require a full function definition.
- Higher-order functions. Work effectively as arguments to higher-order functions like
map()
,filter()
, orsorted()
. - Temporary (throwaway) functions. Useful when a function is needed only once, and defining it with
def
would unnecessarily clutter the code. - Improved Readability. Suitable for simple tasks where using a lambda function keeps the code compact and easy to follow.
When to avoid Lambda functions
- Complex or multiline logic. Lambdas are limited to a single expression and can quickly become unreadable for more intricate operations.
- Reusable or named functions. If the function needs to be reused or benefits from a descriptive name, a standard
def
function is more appropriate. - Debugging or documentation. Lambda functions lack the ability to include docstrings and can be harder to debug compared to named functions.
To enhance readability and maintainability while using lambdas, follow these best practices:
- Use descriptive names for clarity.
- Keep it simple: Lambdas should ideally fit on one line and represent straightforward logic.
- Limit nesting: Avoid using lambda functions within other lambda functions or complex data structures unless necessary.
- Prefer readability to conciseness: If using a lambda sacrifices readability, it's better to define a named function.
Conclusion
Python lambda functions are a powerful tool for writing concise, anonymous functions. They shine in scenarios requiring short, temporary, or inline operations, particularly when used with higher-order functions like map
, filter
, or sorted
.
However, they should be used judiciously, as more complex logic is better suited to standard functions defined with def
. By understanding their strengths, limitations, and best practices, you can effectively leverage lambda functions to write clean, efficient, and maintainable Python code.
To learn more about Python functions, check out DataCamp's resources.
Python Lambda Functions FAQs
Why use a lambda function?
They are perfect for simplifying short-term tasks, streamlining code with higher-order functions like map
, filter
, or sorted
, and reducing clutter when defining temporary or throwaway logic.
When should I use lambda functions?
Lambda functions are appropriate for: short, simple logic, suitable for one-liners, as function arguments to higher-order functions, such as map()
or filter()
, and for temporary functions that are only needed once.
When should I avoid lambda functions?
Lambda functions may not be the best choice for complex logic or functions that require documentation (such as docstrings).

Mark Pedigo, PhD, is a distinguished data scientist with expertise in healthcare data science, programming, and education. Holding a PhD in Mathematics, a B.S. in Computer Science, and a Professional Certificate in AI, Mark blends technical knowledge with practical problem-solving. His career includes roles in fraud detection, infant mortality prediction, and financial forecasting, along with contributions to NASA’s cost estimation software. As an educator, he has taught at DataCamp and Washington University in St. Louis and mentored junior programmers. In his free time, Mark enjoys Minnesota’s outdoors with his wife Mandy and dog Harley and plays jazz piano.
Top DataCamp Courses
Course
Introduction to Functions in Python
Course
Writing Functions in Python
Tutorial
Python lambda Tutorial

DataCamp Team
3 min
Tutorial
Getting Started with AWS Lambda: A Step-by-Step Tutorial
Tutorial
Python Functions: How to Call & Write Functions
Tutorial
Python List Functions & Methods Tutorial and Examples
Tutorial
Python Tuples Tutorial
Tutorial