Python - Prefix sum list

PythonServer Side ProgrammingProgramming

A list is a collection which is ordered and changeable. In Python lists are written with square brackets. You access the list items by referring to the index number. Negative indexing means beginning from the end, -1 refers to the last item. You can specify a range of indexes by specifying where to start and where to end the range. When specifying a range, the return value will be a new list with the specified items.

Example

 Live Demo

# 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))

Output

The original list : [3, 4, 1, 7, 9, 1]
The prefix sum list is : [3, 7, 8, 15, 24, 25]
raja
Published on 06-Aug-2020 13:15:51
Advertisements