Python – Suffix List Sum
Nowdays, especially in the field of competitive programming, the utility of computing suffix 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 : 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# Suffix List Sum# using list comprehension + sum() + list slicing# initializing listtest_list = [3, 4, 1, 7, 9, 1]# printing original listprint("The original list : " + str(test_list))# using list comprehension + sum() + list slicing# Suffix List Sumtest_list.reverse()res = [sum(test_list[ : i + 1 ]) for i in range(len(test_list))]# print resultprint("The suffix sum list is : " + str(res)) |
Output :
The original list : [3, 4, 1, 7, 9, 1] The suffix sum list is : [1, 10, 17, 18, 22, 25]
Method#2: Using a for loop
Python3
def suffix_sum(lst): result = [] sum = 0 for i in range(len(lst) - 1, -1, -1): sum += lst[i] result.append(sum) return resulttest_list = [3, 4, 1, 7, 9, 1]print("The original list :", test_list)res = suffix_sum(test_list)print("The suffix sum list is :", res)#This code is contributed Vinay Pinjala. |
Output
The original list : [3, 4, 1, 7, 9, 1] The suffix sum list is : [1, 10, 17, 18, 22, 25]
Time Complexity: O(n)
Auxiliary Space: O(n)






Please Login to comment...