Python - Incremental Sublist Sum

An incremental sublist sum (also known as cumulative sum) calculates running totals of elements in a list. Each position contains the sum of all elements from the start up to that position.

For example, given the list [10, 20, 30, 40, 50]:

  • Index 0: 10
  • Index 1: 10 + 20 = 30
  • Index 2: 10 + 20 + 30 = 60
  • Index 3: 10 + 20 + 30 + 40 = 100
  • Index 4: 10 + 20 + 30 + 40 + 50 = 150

The result is [10, 30, 60, 100, 150].

Using a Loop

The most straightforward approach uses a loop to accumulate the sum ?

def incremental_sublist_sum(numbers):
    result = []
    current_sum = 0
    for num in numbers:
        current_sum += num
        result.append(current_sum)
    return result

numbers = [100, 50, 120, 60, 30, 40]
cumulative_sum = incremental_sublist_sum(numbers)
print(cumulative_sum)
[100, 150, 270, 330, 360, 400]

Using List Comprehension

List comprehension with slicing provides a more concise solution ?

def incremental_sublist_sum(numbers):
    return [sum(numbers[:i+1]) for i in range(len(numbers))]

numbers = [78, 10, 88, 20]
cumulative_sum = incremental_sublist_sum(numbers)
print(cumulative_sum)
[78, 88, 176, 196]

Using itertools.accumulate()

The accumulate() function from itertools is designed specifically for cumulative operations ?

from itertools import accumulate

def incremental_sublist_sum(numbers):
    return list(accumulate(numbers))

numbers = [23, 43, 10]
cumulative_sum = incremental_sublist_sum(numbers)
print(cumulative_sum)
[23, 66, 76]

Using NumPy

NumPy's cumsum() function efficiently handles large arrays ?

import numpy as np

def incremental_sublist_sum(numbers):
    return np.cumsum(numbers).tolist()

numbers = [11, 21, 31, 41, 51]
cumulative_sum = incremental_sublist_sum(numbers)
print(cumulative_sum)
[11, 32, 63, 104, 155]

Performance Comparison

Method Time Complexity Best For
Loop O(n) Learning and understanding
List Comprehension O(n²) Small lists, one-liners
itertools.accumulate() O(n) General purpose, pure Python
NumPy cumsum() O(n) Large datasets, numerical computing

Conclusion

Use itertools.accumulate() for most cases as it's efficient and readable. For numerical computing with large datasets, NumPy's cumsum() offers superior performance.

Updated on: 2026-03-27T12:17:40+05:30

338 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements