Lambda functions, often referred to as “anonymous functions,” are small, unnamed functions defined using the
lambda keyword. They can have any number of arguments, but only one expression.
The general syntax of a lambda function is:
lambda arguments: expression
The expression is returned upon calling the lambda function.
A simple lambda function that adds two numbers:
add = lambda x, y: x + y print(add(5, 3)) # Output: 8
Notice how the function is defined in a single line and doesn’t have a name.
map() applies a function to all items in the input list. Using lambda with
numbers = [1, 2, 3, 4] squared = list(map(lambda x: x**2, numbers)) print(squared) # Output: [1, 4, 9, 16]
filter() creates a list of elements for which a function returns
True. Using lambda with
numbers = [1, 2, 3, 4, 5] evens = list(filter(lambda x: x % 2 == 0, numbers)) print(evens) # Output: [2, 4]
Lambda functions can help in sorting lists based on custom criteria:
pairs = [(1, 2), (2, 1), (4, 3), (3, 4)] sorted_pairs = sorted(pairs, key=lambda p: p) print(sorted_pairs) # Output: [(2, 1), (1, 2), (4, 3), (3, 4)]
Here, the list of tuples is sorted based on the second item in each tuple.
While lambda functions are powerful, they aren’t always the best choice:
However, if the functionality gets complex, it’s usually more readable and manageable to define a regular function using the
Lambda functions are a distinctive feature of Python, allowing for the creation of quick, unnamed functions for lightweight tasks. While they are a neat tool to have in your Python toolkit, it’s essential to understand when to use them and when to opt for the more traditional function definition for clarity and maintainability.