# Creating an unknown size list in a table calculation

I often would have a calculation, where Table serves the purpose of an effective for loop and I would like to collect some computation in a final list as the Table values are iterated.

As a simple example (Please note that this is not the computation I necessary want to do it is just a representative situation) suppose I want to compute the sum of 10 numbers but save the intermittent calculations in another list, like so:

sum = 0; cumsum = ConstantArray[0, 10];
Table[sum = sum + ii; cumsum[[ii]] = sum;, {ii, 10}];
cumsum


The collection in cumsum requires me to create a constant array. It also requires me to know the size of the array before running the calculation. This code obviously does what I want to do here, but is there a BETTER more Mathematica way of collecting intermittent results in a Table, by saving them in an array that is defined on the spot?

I understand there are possible solutions with

cumsum={}; sum=0;
Table[sum = sum + ii; AppendTo[cumsum,sum];, {ii, 10}];
cumsum


but I am not sure if either of them is the correct way to do it. I apologize if this is a common question, and I appreciate any answers.

When size is not known, I like to use Sow and Reap and use Do instead of Table

ClearAll[sum, cumsum];
sum = 0;
cumsum = First@Last@Reap@Do[sum = sum + i; Sow@sum, {i, 10}] This should be more efficient than AppendTo

ClearAll[sum, cumsum];
sum = 0;
Timing[First@Last@Reap@Do[sum = sum + i; Sow@sum, {i, 100000}]][]
(*0.078 seconds*)

ClearAll[sum, cumsum];
cumsum = {}; sum = 0;
Timing[Table[sum = sum + ii; AppendTo[cumsum, sum], {ii, 100000}]][]
(* 12.2344 *)

• Indeed, Sow+Reap was made for this, and is way better than Append(To). +1 May 4, 2020 at 7:03
• First@Last@Reap@Do[Sow[sum += i], {i, 100000}] a little faster.
– kglr
May 7, 2020 at 7:32