Sometimes, you need a simple function for a very specific, short-lived purpose. Defining a full function using def
might feel like overkill, especially if you only plan to use it in one place, like passing it as an argument to another function. Python provides a way to create small, unnamed (anonymous) functions inline using the lambda
keyword.
Think of lambda functions as shortcuts for creating simple functions defined by a single expression. They are particularly useful when working with functions that operate on other functions, such as map()
, filter()
, or sorted()
.
The structure of a lambda function is straightforward:
lambda arguments: expression
lambda
: The keyword that signifies you are creating an anonymous function.arguments
: One or more argument names, separated by commas, similar to the parameters in a def
function definition.:
: A colon separates the arguments from the expression.expression
: A single expression that is evaluated when the lambda function is called. The result of this expression is automatically returned. Lambda functions cannot contain complex statements like loops, if
/else
blocks (though conditional expressions are allowed), or assignments within their body.lambda
with def
Let's look at a standard function and its lambda equivalent. Suppose we want a function to add two numbers:
# Using a standard function definition
def add(x, y):
return x + y
# Using a lambda function
add_lambda = lambda x, y: x + y
# Both can be called in the same way
result1 = add(10, 5)
result2 = add_lambda(10, 5)
print(f"Result from def function: {result1}") # Output: Result from def function: 15
print(f"Result from lambda function: {result2}") # Output: Result from lambda function: 15
In this example, add_lambda
is a variable that holds the lambda function. While you can assign a lambda function to a variable like this, it somewhat defeats the purpose of them being anonymous. Their main strength lies in being defined directly where they are needed, often as arguments to other functions.
Lambda functions shine when used with functions that accept another function as an argument (often called higher-order functions).
lambda
with map()
The map()
function applies a given function to each item of an iterable (like a list) and returns a map object (which can be converted to a list). Lambdas are perfect for providing the function argument to map()
concisely.
numbers = [1, 2, 3, 4, 5]
# Use map with a lambda function to square each number
squared_numbers = map(lambda x: x * x, numbers)
# Convert the map object to a list to see the results
print(list(squared_numbers)) # Output: [1, 4, 9, 16, 25]
Here, lambda x: x * x
is the anonymous function passed to map()
. It takes one argument x
and returns x * x
. map()
applies this lambda to every element in the numbers
list.
lambda
with filter()
The filter()
function constructs an iterator from elements of an iterable for which a function returns true. Lambda functions are ideal for defining the filtering condition.
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Use filter with a lambda function to get only even numbers
even_numbers = filter(lambda x: x % 2 == 0, numbers)
# Convert the filter object to a list
print(list(even_numbers)) # Output: [2, 4, 6, 8, 10]
The lambda lambda x: x % 2 == 0
checks if a number is even (returns True
if it is, False
otherwise). filter()
uses this condition to select elements from the numbers
list.
lambda
with sorted()
The sorted()
function can take an optional key
argument, which is a function used to extract a comparison key from each element. Lambdas are frequently used here to specify simple sorting criteria.
# List of tuples (name, age)
people = [('Alice', 30), ('Bob', 25), ('Charlie', 35)]
# Sort the list by age (the second element of each tuple)
sorted_by_age = sorted(people, key=lambda person: person[1])
print(sorted_by_age) # Output: [('Bob', 25), ('Alice', 30), ('Charlie', 35)]
The lambda lambda person: person[1]
takes a tuple person
and returns its second element (person[1]
, which is the age). sorted()
uses these ages as the keys for sorting the list.
While lambda functions offer conciseness, they have limitations:
x if condition else y
), or try
/except
blocks.def
function with a descriptive name and potentially comments is usually much more readable and maintainable than a convoluted lambda function.Use lambda functions when the operation is simple and the conciseness improves clarity, typically when passing a function as an argument. If the logic starts getting even slightly complex, prefer defining a regular function with def
.
In summary, lambda functions provide a compact syntax for creating small, anonymous functions defined by a single expression. They are most effectively used as arguments to higher-order functions like map()
, filter()
, and sorted()
, allowing you to define simple operations directly where they are needed without the boilerplate of a full def
statement.
© 2025 ApX Machine Learning