The reduce()
function, from the functools
module, applies a function cumulatively to the items of an iterable, reducing it to a single value. It's often used for aggregations like summing or multiplying.
from functools import reduce
reduce(function, iterable[, initializer])
# 1. Summing elements
from functools import reduce
numbers = [1, 2, 3, 4]
total = reduce(lambda x, y: x + y, numbers)
print(total) # Output: 10
# 2. Multiplying elements
numbers = [1, 2, 3, 4]
product = reduce(lambda x, y: x * y, numbers)
print(product) # Output: 24
# 3. Finding the maximum value
numbers = [3, 8, 2, 5]
maximum = reduce(lambda x, y: x if x > y else y, numbers)
print(maximum) # Output: 8
# 4. Using an initializer
numbers = [1, 2, 3]
total = reduce(lambda x, y: x + y, numbers, 10)
print(total) # Output: 16 (10 + 1 + 2 + 3)
# 5. Concatenating strings
words = ["Hello", "World", "!"]
sentence = reduce(lambda x, y: x + " " + y, words)
print(sentence) # Output: Hello World !