Home >Backend Development >Python Tutorial >How Can I Efficiently Calculate the Cumulative Sum of a List of Numbers in Python?

How Can I Efficiently Calculate the Cumulative Sum of a List of Numbers in Python?

Susan Sarandon
Susan SarandonOriginal
2024-12-10 11:39:14570browse

How Can I Efficiently Calculate the Cumulative Sum of a List of Numbers in Python?

Finding the Cumulative Sum of Numbers in a List

Problem:
Given a list of numbers, we want to find the cumulative sum, which means summing up the numbers one by one from the beginning of the list. For instance, if we have a list [4, 6, 12], we want to get [4, 4 6, 4 6 12] resulting in [4, 10, 22].

Answer:

For numerical operations on arrays, it's recommended to consider NumPy, a powerful Python library. It features a convenient cumulative sum function, cumsum:

import numpy as np

a = [4,6,12]

np.cumsum(a)
#array([4, 10, 22])

NumPy often outperforms pure Python for such tasks. Here's a comparison with another function, accumu:

In [136]: timeit list(accumu(range(1000)))
10000 loops, best of 3: 161 us per loop

In [137]: timeit list(accumu(xrange(1000)))
10000 loops, best of 3: 147 us per loop

In [138]: timeit np.cumsum(np.arange(1000))
100000 loops, best of 3: 10.1 us per loop

While NumPy offers speed advantages, it's important to remember that a dependency may not be necessary if NumPy is only required for a single task.

The above is the detailed content of How Can I Efficiently Calculate the Cumulative Sum of a List of Numbers in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn