Skip to content
Related Articles

Related Articles

Python | Prefix sum list

View Discussion
Improve Article
Save Article
  • Last Updated : 13 Jun, 2022
View Discussion
Improve Article
Save Article

Nowadays, especially in the field of competitive programming, the utility of computing prefix sum is quite popular and features in many problems. Hence, having a one-liner solution to it would possess a great help. Let’s discuss certain way in which this problem can be solved. 

Method #1: Using list comprehension + sum() + list slicing This problem can be solved using the combination of above two functions in which we use list comprehension to extend logic to each element, sum function to get the sum along, slicing is used to get sum till the particular index. 

Python3




# Python3 code to demonstrate
# prefix sum list
# using list comprehension + sum() + list slicing
 
# initializing list
test_list = [3, 4, 1, 7, 9, 1]
 
# printing original list
print("The original list : " + str(test_list))
 
# using list comprehension + sum() + list slicing
# prefix sum list
res = [sum(test_list[ : i + 1]) for i in range(len(test_list))]
 
# print result
print("The prefix sum list is : " + str(res))

  Method #2: Using accumulate(iterable) method.

Python3




# function to find cumulative sum of list
from itertools import accumulate
 
def cumulativeSum(lst):
    print (list(accumulate(lst)))
 
# Driver program
if __name__ == "__main__":
    lst = [3, 4, 1, 7, 9, 1]
    cumulativeSum(lst)

Output: 

[3, 7, 8, 15, 24, 25]

Method#3: Using For loop and list indexing The above problem can be solve using two mention techniques. For loop is used for iterating in list and list indexing is used to access current element and previous element. 

Python3




# Python3 code to demonstrate
# prefix sum list
# using For loop + list indexing
 
# initializing list
test_list = [3, 4, 1, 7, 9, 1]
 
# printing original list
print("The original list : " + str(test_list))
 
# using For loop and list indexing
# prefix sum list
res = [0]*len(test_list)
res[0] = test_list[0]
for i in range(1, len(test_list)):
    res[i] = res[i-1] + test_list[i]
 
# print result
print("The prefix sum list is : " + str(res))

Output

The original list : [3, 4, 1, 7, 9, 1]
The prefix sum list is : [3, 7, 8, 15, 24, 25]

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!