Practical Applications of Anonymous Functions
Using Anonymous Functions with Higher-Order Functions
One of the most common use cases for anonymous functions in Python is in combination with higher-order functions, such as map()
, filter()
, and reduce()
. These functions take another function as an argument, making anonymous functions a perfect fit.
## Using map() with an anonymous function
numbers = [1, 2, 3, 4, 5]
squared_numbers = list(map(lambda x: x**2, numbers))
print(squared_numbers) ## Output: [1, 4, 9, 16, 25]
## Using filter() with an anonymous function
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers) ## Output: [2, 4]
## Using reduce() with an anonymous function
from functools import reduce
product = reduce(lambda x, y: x * y, numbers)
print(product) ## Output: 120
Sorting with Anonymous Functions
Anonymous functions can also 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}]
Conditional Expressions with Anonymous Functions
Anonymous functions can also be used in conditional expressions, also known as ternary operators, to create more concise and readable code.
age = 18
is_adult = "Yes" if age >= 18 else "No"
print(is_adult) ## Output: Yes
In this example, the anonymous function lambda age: "Yes" if age >= 18 else "No"
is used as the conditional expression to determine whether the person is an adult or not.
These are just a few examples of the practical applications of anonymous functions in Python. They can be a powerful tool when used in the right context, helping to make your code more concise and expressive.