Python lambda functions are essential for concise and functional programming by allowing quick creation of anonymous functions for tasks that require short and simple operations.
A Python lambda function is a small anonymous function defined with the lambda
keyword. It allows you to create a function on-the-fly without a proper function definition using def
.
Syntax
lambda arguments: expression
Example
Let’s say you want to create a lambda function that adds two numbers. Here, lambda x, y: x + y
creates a lambda function that takes two arguments (x
and y
) and returns their sum (x + y
).
add = lambda x, y: x + y
This lambda function is equivalent to the following regular function:
def add(x, y):
return x + y
Using Lambda Functions
Lambda functions are often used in situations where you need a short function for a short period of time. They are commonly used with functions like map()
, filter()
, and reduce()
in functional programming paradigms. For example:
# Using lambda with map
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
print(squared) # Output: [1, 4, 9, 16, 25]
# Using lambda with filter
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) # Output: [2, 4, 6, 8, 10]
Returning Values
Lambda functions automatically return the result of the expression evaluated. You don’t need to use a return
statement explicitly. For example:
multiply = lambda x, y: x * y
result = multiply(4, 6)
print(result) # Output: 24
Python’s sorted
Lambda functions are commonly used with Python’s sorted()
function to define custom sorting criteria. For instance, sorting a list of tuples based on the second element:
pairs = [(1, 'one'), (3, 'three'), (2, 'two'), (4, 'four')]
sorted_pairs = sorted(pairs, key=lambda x: x[1])
print(sorted_pairs) # Output: [(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
Mapping a lambda over a list
You can work with a list.
numbers = [1, 2, 3, 4, 5]
doubled = list(map(lambda x: x * 2, numbers))
print(doubled) # Output: [2, 4, 6, 8, 10]