How to calculate the sum of elements in a list

Posted in Python by Dirk - last update: Feb 02, 2024

The easiest way to calculate the sum of the elements in a list using the built-in sum() function. It works for all Python versions

my_list = [1, 2, 3, 4, 5]
total = sum(my_list)
print(total)  # Output: 15

Alternatives

Using a ‘for’ loop

This method iterates over each element in the list and adds it to a running total.

my_list = [1, 2, 3, 4, 5]
total = 0
for num in my_list:
    total += num
print(total)  # Output: 15

Using the numpy library

numpy.sum() computes the sum of array elements over a specified axis. In this case, it sums all elements in the list.

import numpy as np
my_list = [1, 2, 3, 4, 5]
total = np.sum(my_list)
print(total)  # Output: 15

Dependency: the numpy library needs to be installed (pip install numpy).

Using the functools.reduce() function with operator.add

The functools.reduce() applies a rolling computation to sequential pairs of values in the list, using the operator.add function to add them up.

Using a generator expression

This method uses a generator expression within the sum() function to calculate the sum of elements in the list.

my_list = [1, 2, 3, 4, 5]
total = sum(num for num in my_list)
print(total)  # Output: 15

Other articles