Prefix Sum Array in Python using Accumulate Function Last Updated : 17 Jan, 2025 Comments Improve Suggest changes Like Article Like Report A prefix sum array is an array where each element is the cumulative sum of all the previous elements up to that point in the original array. For example, given an array [1, 2, 3, 4], its prefix sum array would be [1, 3, 6, 10]. Let us explore various methods to achieve this.Using accumulate from itertoolsThis method utilizes the accumulate() function from the itertools module, which is specifically designed to calculate cumulative results like prefix sums. Python # Import accumulate from itertools from itertools import accumulate # Input array a = [1, 2, 3, 4] # Calculate prefix sum array prefix_sum = list(accumulate(a)) print(prefix_sum) Output[1, 3, 6, 10] Explanation:accumulate() function computes the cumulative sum of elements in the array.We convert the result into a list to display the prefix sum array.Let's explore some more methods and see how we can calculate prefix sum array in Python using accumulate function.Table of ContentUsing list comprehensionUsing numpyUsing for loopUsing reduce from functoolsUsing list comprehensionThis method uses list comprehension along with a running total to create the prefix sum array in a concise manner. Python # Input array a = [1, 2, 3, 4] # Initialize a running total total = 0 # Calculate prefix sum using list comprehension prefix_sum = [total := total + num for num in a] print(prefix_sum) Output[1, 3, 6, 10] Explanation:We use the walrus operator (:=) to update the total while iterating over the array.The prefix sum is constructed as a list directly.This approach combines the functionality of a loop and inline calculation into a single line.Using numpyFor numerical data, numpy provides an efficient way to compute prefix sums using its cumsum function for calculating prefix sums. Python # Import numpy import numpy as np # Input array a = [1, 2, 3, 4] # Calculate prefix sum using numpy prefix_sum = np.cumsum(a) print(prefix_sum.tolist()) Output[1, 3, 6, 10] Explanation:cumsum function from numpy computes the cumulative sum efficiently.The resulting array is converted to a list for easier readability.Using for loopA simple approach is to use a for loop to calculate the prefix sum by iterating through the array and maintaining a running total. Python # Input array a = [1, 2, 3, 4] # Initialize an empty prefix sum array and a running total p_sum = [] total = 0 # Calculate prefix sum using a loop for num in a: total += num p_sum.append(total) print(p_sum) Output[1, 3, 6, 10] Explanation:We maintain a running total using a variable, which is updated with each element of the array.Each element is added to total, and the result is appended to the prefix sum array.Using reduce from functoolsThis method uses the reduce() function to calculate the prefix sum array step by step. Python # Import reduce from functools from functools import reduce # Input array a = [1, 2, 3, 4] # Calculate prefix sum using reduce p_sum = [reduce(lambda x, y: x + y, a[:i+1]) for i in range(len(a))] print(p_sum) Output[1, 3, 6, 10] Explanation:reduce() function is used to calculate the cumulative sum for each slice of the array.Although functional, this method is less efficient than the others due to repeated slicing. Comment More infoAdvertise with us Next Article Prefix Sum Array in Python using Accumulate Function S Shashank Mishra Follow Improve Article Tags : Python DSA Arrays python-list Practice Tags : Arrayspythonpython-list Similar Reads Sum 2D array in Python using map() function Given a 2-D matrix, we need to find sum of all elements present in matrix ? Examples: Input : arr = [[1, 2, 3], [4, 5, 6], [2, 1, 2]] Output : Sum = 26 This problem can be solved easily using two for loops by iterating whole matrix but we can solve this problem quickly in python using map() function 2 min read pandas.array() function in Python This method is used to create an array from a sequence in desired data type. Syntax : pandas.array(data: Sequence[object], dtype: Union[str, numpy.dtype, pandas.core.dtypes.base.ExtensionDtype, NoneType] = None, copy: bool = True) Parameters : data : Sequence of objects. The scalars inside `data` sh 2 min read Array in Python | Set 1 (Introduction and Functions) Other than some generic containers like lists, Python in its definition can also handle containers with specified data types. The array can be handled in Python by a module named "array". They can be useful when we have to manipulate only specific data type values. Properties of ArraysEach array ele 7 min read Array in Python | Set 2 (Important Functions) Array in Python | Set 1 (Introduction and Functions)Array in Python | Set 2Below are some more useful functions provided in Python for arrays: Array Typecode FunctionThis function returns the data type by which the array is initialized. In this example, we are using arr.typecode to find out the data 3 min read sum() function in Python The sum of numbers in the list is required everywhere. Python provides an inbuilt function sum() which sums up the numbers in the list. Pythonarr = [1, 5, 2] print(sum(arr))Output8 Sum() Function in Python Syntax Syntax : sum(iterable, start) iterable : iterable can be anything list , tuples or dict 3 min read Python Program to Find Sum of Array Given an array of integers, find the sum of its elements. Examples: Input : arr[] = {1, 2, 3}Output : 6Explanation: 1 + 2 + 3 = 6This Python program calculates the sum of an array by iterating through each element and adding it to a running total. The sum is then returned. An example usage is provid 4 min read Find the increased sum of the Array after P operations Given an array arr[] of non-negative integers of size N and an integer P. Neighboring values of every non-zero element are incremented by 2 in each operation, the task is to find the increased sum of the array after P operations. Examples: Input: arr[] = {0, 5, 0, 4, 0}, P = 2Output: 24Explanation: 12 min read Numpy recarray.cumsum() function | Python In numpy, arrays may have a data-types containing fields, analogous to columns in a spreadsheet. An example is [(a, int), (b, float)], where each entry in the array is a pair of (int, float). Normally, these attributes are accessed using dictionary lookups such as arr['a'] and arr['b']. Record array 2 min read Indexing Multi-dimensional arrays in Python using NumPy In this article, we will cover the Indexing of Multi-dimensional arrays in Python using NumPy. NumPy is a general-purpose array-processing package. It provides a high-performance multidimensional array object and tools for working with these arrays. It is the fundamental package for scientific compu 3 min read Prefix Sum Array - Implementation and Applications Given an array arr[] of size n, the task is to find the prefix sum of the array. A prefix sum array is another array prefixSum[] of the same size, such that prefixSum[i] is arr[0] + arr[1] + arr[2] . . . arr[i].Examples: Input: arr[] = [10, 20, 10, 5, 15]Output: 10 30 40 45 60Explanation: For each i 8 min read Like