Skip to content

How to use Python reduce()

New Course Coming Soon:

Get Really Good at Git

Python provides 3 useful global functions we can use to work with collections: map(), filter() and reduce().

Tip: sometimes list comprehensions make more sense and are generally considered more pythonic

reduce() is used to calculate a value out of a sequence, like a list.

For example suppose you have a list of expenses, stored as tuples, and you want to calculate the sum of a property property in each tuple, in this case the cost of each expense:

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

You could iterate with a loop over them:

sum = 0
for expense in expenses:
    sum += expense[1]

print(sum) # 200

Or, you can use reduce() to reduce the list to a single value:

from functools import reduce

print(reduce(lambda a, b: a[1] + b[1], expenses)) # 200

reduce() is not available by default like map() and filter(). You need to import it from the standard library module functools.

Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching May 21, 2024. Join the waiting list!
→ Get my Python Handbook
→ Get my Python Handbook

Here is how can I help you: