How to Use Python reduce() to Calculate Values from a Sequence
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):
1 | expenses = [ |
One way to achieve this is by iterating over the list using a loop:
1 | total = 0 |
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:
1 | from functools import reduce |
Note: Unlike
map()
andfilter()
,reduce()
is not available by default. You need to import it from thefunctools
module.
Tags: Python, reduce, sequence, calculation