98. functools.reduce
Here are 10 Python code snippets demonstrating how to use functools.reduce to apply a binary function cumulatively to items of an iterable:
1. Summing Numbers in a List
from functools import reduce
numbers = [1, 2, 3, 4, 5]
result = reduce(lambda x, y: x + y, numbers)
print(result) # Output: 152. Finding the Product of Numbers
from functools import reduce
numbers = [1, 2, 3, 4, 5]
result = reduce(lambda x, y: x * y, numbers)
print(result) # Output: 1203. Finding the Maximum Value
from functools import reduce
numbers = [5, 3, 8, 2, 7]
result = reduce(lambda x, y: x if x > y else y, numbers)
print(result) # Output: 84. Flattening a Nested List
5. Concatenating Strings
6. Calculating Factorial
7. Counting Character Frequencies
8. Finding the Greatest Common Divisor (GCD)
9. Merging Dictionaries
10. Calculating Dot Product
These examples show the versatility of functools.reduce, which can be used in a wide range of scenarios, from simple numerical operations to more complex tasks like dictionary merging or working with nested structures.
Last updated