How to use Python reduce()
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 likemap()
andfilter()
. You need to import it from the standard library modulefunctools
.
→ I wrote 17 books to help you become a better developer:
- C Handbook
- Command Line Handbook
- CSS Handbook
- Express Handbook
- Git Cheat Sheet
- Go Handbook
- HTML Handbook
- JS Handbook
- Laravel Handbook
- Next.js Handbook
- Node.js Handbook
- PHP Handbook
- Python Handbook
- React Handbook
- SQL Handbook
- Svelte Handbook
- Swift Handbook
Also, JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025