Python | Prefix sum list
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 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)) |
The original list : [3, 4, 1, 7, 9, 1] The prefix sum list is : [3, 7, 8, 15, 24, 25]
Method #2: Using accumulate(iterable) method.
# 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]
Recommended Posts:
- Python | Split strings in list with same prefix in all elements
- Python | Append suffix/prefix to strings in list
- Python | Get the numeric prefix of given string
- Python | Get numeric prefix of given string
- Python | Prefix key match in dictionary
- Prefix sum array in Python using accumulate function
- Prefix matching in Python using pytrie module
- Python | Prefix Sum Subarray till False value
- Python | Prefix extraction before specific character
- Python program to print the substrings that are prefix of the given string
- Python | Ways to determine common prefix in set of strings
- Python | Convert list of tuples to list of list
- Python | Convert list of string to list of list
- Python program to create a list of tuples from given list having number and its cube in each tuple
- Python | Convert list of string into sorted list of integer
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



