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
Copy
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
Copy
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
Copy
4. Flattening a Nested List
Copy
5. Concatenating Strings
Copy
6. Calculating Factorial
Copy
7. Counting Character Frequencies
Copy
8. Finding the Greatest Common Divisor (GCD)
Copy
9. Merging Dictionaries
Copy
10. Calculating Dot Product
Copy
Last updated