# How to sum over a List

list = {11.5575, 11.397, 5.52734, 4.0878, 2.54815, 1.86652, 2.55028,
2.14952, 1.6242, 1.34117}


I have a list of numbers. How do I make a function that creates a new list, where the first entry is equal to

{list[[1]], list[[1]] + list[[2]], list[[1]] + list [[2]] + list[[3]]}


etc until the end of the list. I ask because my real list is quite a bit longer than just 10 entries, and writing this out would get far too long to handle.

-
This operation is known formally as the prefix sum. You may wish to investigate its parallel variants, an efficient implementation of which which could potentially outperform Accumulate. –  Oleksandr R. Apr 21 at 5:33
For reference, for anyone searching, because it's what the title seems to ask, easy ways to sum a list (without accumulation of results) are Plus@@list and Total[list] –  NeuroFuzzy Apr 21 at 8:26

Accumulate is absolutely the most idiomatic and appropriate answer here. However since Mathematica is very powerful at list manipulation, it might be illustrative to show you couple of other ways of doing the same thing, just so you learn to think outside of mainstream procedural ways.

### 1. Using FoldList:

This is a functional way of doing exactly what you wrote by hand, and probably the first option you should be thinking of, if Accumulate were not available.

Rest@FoldList[Plus, 0, list]


The advantage of knowing this method, is that you can use it for other operations and not just addition.

### 2. Using ReplaceList

ReplaceList is very powerful when you want to apply the same operation (here Plus) to all possible results of a particular pattern (here, one that gives increasingly longer sublists starting with the first element).

ReplaceList[list, {h__, ___} :> Plus[h]]


Both the above approaches give you the same answer as Accumulate@list

-

Easy Solution

v = Accumulate[list]


Gives Output

{11.5575, 22.9545, 28.4819, 32.5697, 35.1178, 36.9843, 39.5346, \
41.6841, 43.3083, 44.6495}

-

Just for fun, here's a recursive approach:

accSum[{}] := {}; accSum[{x_}] := {x};
accSum[{r___, x1_}] := Join[{Total[{r, x1}]}, accSum[{r}]];


Usage:

list = {11.5575, 11.397, 5.52734, 4.0878, 2.54815, 1.86652, 2.55028,
2.14952, 1.6242, 1.34117}

accSum[list] // Reverse


Gives:

{11.5575, 22.9545, 28.4818, 32.5696, 35.1178, 36.9843, 39.5346, 41.6841, 43.3083, 44.6495}


Updated

Here's an updated version of the above recursive function, it's shorter and there's no need to reverse the list obtained.

accSum2[{x___}] := {x};
accSum2[{r___, x_}] := Join[accSum2[{r}], {Total[{r, x}]}];

accSum2[list]

{11.5575, 22.9545, 28.4818, 32.5696, 35.1178, 36.9843, 39.5346, 41.6841, 43.3083, 44.6495}

-