Lambda functions in Python are concise, anonymous functions defined using the lambda keyword. Unlike regular functions defined with def, lambda functions are typically used for short-lived operations where naming a function might seem excessive. They can take any number of arguments but only return a single expression.
lambda arguments: expression
• arguments: Any number of arguments (comma-separated).
• expression: A single expression that is evaluated and returned.
Lambda functions are often used when a function is required for a short period, such as in higher-order functions (map(), filter(), sorted(), etc.).
1. Basic Example
add = lambda x, y: x + y
print(add(5, 3)) # Output: 8
The filter() function is used to filter elements from an iterable based on a function that returns True or False.
numbers = [1, 2, 3, 4, 5]
odd_numbers = list(filter(lambda x: x % 2 != 0, numbers))
print(odd_numbers) # Output: [1, 3, 5]
The map() function applies a function to all items in an iterable.
numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x ** 2, numbers))
print(squared_numbers) # Output: [1, 4, 9, 16, 25]
Lambda functions can be used within list comprehensions for more concise code.
squares = [(lambda x: x ** 2)(x) for x in range(11)]
print(squares) # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
Lambda functions can include conditional expressions to perform different actions based on a condition.
max_value = lambda x, y: x if x > y else y
print(max_value(10, 20)) # Output: 20
Lambda functions are limited to a single expression. However, you can nest lambdas or use them in combination to achieve complex behavior.
list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
sorted_list = sorted(list_of_lists, key=lambda x: x[2])
print(sorted_list) # Output: [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Lambda functions are powerful tools for writing concise, functional code. They are useful for simple operations where a full function definition might be unnecessarily verbose. However, for more complex operations or functions with multiple statements, it's often better to use the def keyword to define a named function.