Applying Lambda Functions in Python
Using Lambda Functions with Built-in Functions
Lambda functions are often used in combination with other built-in functions in Python, such as map()
, filter()
, and reduce()
.
Example 1: Using map()
with Lambda Functions
The map()
function applies a given function to each item of an iterable (such as a list, tuple, or string) and returns an iterator with the modified items.
numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x**2, numbers))
print(squared_numbers) ## Output: [1, 4, 9, 16, 25]
Example 2: Using filter()
with Lambda Functions
The filter()
function creates a new iterator with the elements from the original iterable that pass the test implemented by the provided function.
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]
Example 3: Using reduce()
with Lambda Functions
The reduce()
function applies a function of two arguments cumulatively to the elements of a sequence, from left to right, to reduce the sequence to a single value.
from functools import reduce
numbers = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x * y, numbers)
print(product) ## Output: 120
Sorting with Lambda Functions
Lambda functions can be used as the key
argument in the sorted()
function to customize the sorting behavior.
people = [
{"name": "Alice", "age": 25},
{"name": "Bob", "age": 30},
{"name": "Charlie", "age": 20},
]
## Sort by name
sorted_by_name = sorted(people, key=lambda x: x["name"])
print(sorted_by_name)
## Output: [{'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}, {'name': 'Charlie', 'age': 20}]
## Sort by age
sorted_by_age = sorted(people, key=lambda x: x["age"])
print(sorted_by_age)
## Output: [{'name': 'Charlie', 'age': 20}, {'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 30}]
In the next section, we'll explore how to optimize lambda functions for efficiency.