# How to use Python reduce()

> Learn how to use Python reduce() to calculate a single value from a list, like summing expenses, using a lambda and importing it from functools.

Author: Flavio Copes | Published: 2021-02-28 | Canonical: https://flaviocopes.com/python-reduce/

[Python](https://flaviocopes.com/python-introduction/) provides 3 useful global functions we can use to work with collections: `map()`, `filter()` and `reduce()`.

> Tip: sometimes [list comprehensions](https://flaviocopes.com/python-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:

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

You could iterate with a loop over them:

```python
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:

```python
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`.
