When working with collections in Python, there are three global functions that can be quite useful: map(), filter(), and reduce().

Tip: In some cases, using list comprehensions may be more intuitive and is generally considered more “pythonic”.

In this blog post, we will focus on the reduce() function, which is used to calculate a single value from a sequence, such as a list.

Let’s consider a scenario where you have a list of expenses stored as tuples, and you want to calculate the sum of a specific property in each tuple (in this case, the cost of each expense):

expenses = [
    ('Dinner', 80),
    ('Car repair', 120)
]

One way to achieve this is by iterating over the list using a loop:

total = 0
for expense in expenses:
    total += expense[1]
    
print(total)  # Output: 200

However, a more elegant solution is to use the reduce() function to reduce the list to a single value. To use reduce(), you need to import it from the functools module of the standard library:

from functools import reduce

total = reduce(lambda a, b: a[1] + b[1], expenses)

print(total)  # Output: 200

Note: Unlike map() and filter(), reduce() is not available by default. You need to import it from the functools module.

Tags: Python, reduce, sequence, calculation