# Calculate Cumulative Mean and Standard Deviation of a list without FOR loops [duplicate]

I have a simple list mylist={x_1,x_2,...,x_N};.

Now I want to map a function over this list, e.g. the Mean and StandardDeviation functions, so that it will give me a list that looks like this:

f/@mylist = {f[{x_1}], f[{x_1, x_2}], f[{x_1, x_2, x_3}], ... , f[{x_1,x_2,...,x_N}]}


How can I achieve that? I know that I can use a simple loop to do so but I am wondering if Mathematica has a specific function for this kind of mapping.

Thanks a bunch!

## marked as duplicate by Kuba♦, xzczd, xyz, Martin Ender, MarcoBApr 11 '16 at 13:32

• Would using Table be an acceptable solution or would that count as a simple loop? While Mathematica has Accumulate which performs the operation you look for for Plus, I don't think there's a way to do a generalised accumulation with an arbitrary function like Mean. Neither is there a built-in to get all the prefixes of a list, so I guess using Table or Array might be the best you can get. (E.g. Table[Mean@myList[[1 ;; i]], {i, Length@myList}]) – Martin Ender Apr 11 '16 at 10:23
• mylist = {x1, x2, x3, xN}. f@Take[mylist, #] & /@ Range[4] or Mean@Take[mylist, #] & /@ Range[4], maybe – user1066 Apr 11 '16 at 10:54
• In the lines of @TomD, you could define a helper function for this: ClearAll[MapAccumulate]; MapAccumulate[f_, list_List] := f@Take[list, #] & /@ Range@Length@list; ... MapAccumulate[f, mylist] – kirma Apr 11 '16 at 11:34
• @MartinBüttner I would say it is still acceptable, at least for me. :-) – Minh N Apr 11 '16 at 11:49
• @Kuba: I think it is safe to say that. – Minh N Apr 11 '16 at 11:51

Turning my comment into an answer:

ClearAll[MapAccumulate];

MapAccumulate[f_, list_List] := f@Take[list, #] & /@ Range@Length@list;


Now you can do stuff like this:

MapAccumulate[Mean, mylist]


Aye carumbah - new versions

lis = {x1, x2, x3, x4};


• Sol1:

FoldList[Append, {}, lis] // Rest


{{x1}, {x1, x2}, {x1, x2, x3}, {x1, x2, x3, x4}}

• Sol2:

sol = FoldList[Join, lis]  /. Join->List


{x1, {x1, x2}, {x1, x2, x3}, {x1, x2, x3, x4}}

One can then Map any desired function, e.g.

Map[Mean, sol]


Above work for numerical versions too.

Earlier Suggestion

My earlier suggestion (see comments from Kuba below) was:

Accumulate[lis] /. Plus -> List


... but that has some behavioural problems with numerical input.

• Try this on Range[5]. – Kuba Apr 11 '16 at 11:11
• Trouble maker ! ;) – wolfies Apr 11 '16 at 11:12
• Ah, at least you've confessed :) – Kuba Apr 11 '16 at 11:19
• This is also problematic if f[{x}] != x for all single-element lists. – Martin Ender Apr 11 '16 at 11:23
• I found this only works for symbolic lists. :( – Minh N Apr 11 '16 at 11:52