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.
Answer
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
Comments
Post a Comment