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

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

Patricia Arquette
Patricia ArquetteOriginal
2024-12-09 15:56:16225browse

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

Cumulative Sum in Python

Question:

How can we find the cumulative sum of numbers in a list, like [4, 4 6, 4 6 12]?

Introduction:

Calculating the cumulative sum involves repeatedly adding the next element to the running sum. While this can be achieved with a straightforward loop, there are more efficient approaches using NumPy or custom Python generators.

NumPy Method:

NumPy's cumsum function provides an efficient solution:

import numpy as np

time_interval = [4, 6, 12]
np.cumsum(time_interval)
# Output: [4, 10, 22]

This approach is highly optimized and recommended for numerical operations on large arrays.

Python Generator:

For concise and memory-efficient solutions in pure Python, consider using a generator:

def accumu(iterable):
    yield next(iterable)
    for item in iterable:
        yield item + sum(accumu(iterable))

Using this generator:

list(accumu(time_interval))
# Output: [4, 10, 22]

This generator lazily accumulates elements, making it suitable for iterating over large sequences or when memory is a concern.

The above is the detailed content of How Can I Efficiently Calculate the Cumulative Sum of a List 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