# Sum a list of numbers in Python

**URL:** https://sentry.io/answers/sum-a-list-of-numbers-in-python/

---

## The Problem

In Python, how do I add all the numbers in a list to get a total?

## The Solution

Python provides a built-in [`sum`](https://docs.python.org/3/library/functions.html#sum) function, which returns the sum of all items in an iterable (such as a list). For example:

```python
numbers = [1, 2, 3, 4, 5]

total = sum(numbers)
print(total) # Will print 15 (1 + 2 + 3 + 4 + 5)
```

`sum` is an example of a [*fold* (also called *reduce*)](https://en.wikipedia.org/wiki/Fold_%28higher-order_function%29), which is a type of higher-order functions that produces a single result from a sequence of items. It does this by applying a function (in this case, addition) to the first two items (1 + 2), getting a result (3) and then applying the same function to that result and the next item (3 + 4). This process continues until the list is consumed, and then the final result is returned.

`sum` takes an optional `start` parameter, which provides a first value to use in the first addition. For example:

```python
numbers = [1, 2, 3, 4, 5]

total = sum(numbers, 6)
print(total) # Will print 21 (6 + 1 + 2 + 3 + 4 + 5)
```

We can write our own folds using the [`reduce`](https://docs.python.org/3/library/functools.html?#functools.reduce) function from Python's built-in [`functools`](https://docs.python.org/3/library/functools.html?#module-functools) module. For example, here's how we might find the product of all numbers in a list:

```python
from functools import reduce

numbers = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x * y, numbers)

print(product)  # Will print 120 (1 * 2 * 3 * 4 * 5)
```

We supply `reduce` with two arguments: a function which takes two arguments and a list. It will then apply this function to the contents of the list in the manner described above, ultimately producing a single result. We've used an anonymous [lambda function](https://docs.python.org/3/reference/expressions.html#lambda) here, but `reduce` will also work with a standard function, as below:

```python
from functools import reduce

def multiply(x, y):
    return x * y

numbers = [1, 2, 3, 4, 5]
product = reduce(multiply, numbers)

print(product)  # Will print 120 (1 * 2 * 3 * 4 * 5)
```

`reduce` supports an optional `initializer` parameter, which works the same as the `start` parameter in `sum`.

```python
from functools import reduce

numbers = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x * y, numbers, 6)

print(product)  # Will print 720 (6 * 1 * 2 * 3 * 4 * 5)
```

---

*Source: [sentry.io/answers/sum-a-list-of-numbers-in-python/](https://sentry.io/answers/sum-a-list-of-numbers-in-python/)*
