# How do I get a Do function to create a list?

I have a Do function which gives me a column of expressions. How can I get the Do function to give me these expressions in a list.

i.e The do function gives me this: a b c d

I would like it do give me this: {a,b,c,d}

• "The do function gives me this: a b c d" -- I do not even know how to interpret this. You need to be much more specific. Maybe you want to use Append somehow? Oct 20, 2014 at 15:10
• i'm going to guess you have a Print[] in the do? Oct 20, 2014 at 16:11

While belisarius is right that you can usually make the list you want directly with Table, I'm often in a situation where I need to build up a list with a Do loop. Say I'm numerically propagating a wave function through a series of discrete time steps and need to collect the expectation values for several operators at each time point, this is how I do it.

(*Initialize the list outside the loop*)
list1 = {};
list2 = {};
Do[
(*code here*)
AppendTo[list1,value1];
AppendTo[list2,value2];
,{n,ninit,nfin,nstep}];

• have a look at Reap/Sow Oct 20, 2014 at 16:13
• AppendTo will lead to $O(n^2)$ complexity. Reap/Sow will be much faster when collecting lots of results. Oct 20, 2014 at 19:13
• I can change it to use Reap/Sow but don't really see much improvement. When I run something like what I have written above, the part inside (code here) takes orders of magnitude longer to run than the AppendTo statements. Also I don't see how to use Reap to generate multiple lists, aside from doing something like biglist=Reap[Do[(*code here*)Sow[{value1,value2}];,{n,ninit,nfin,nstep}]][[2,1]]; and then after the loop is done, doing {list1,list2}=Transpose[biglist];. So in my code this will only shave off at most 1% of the execution time, but I suppose every bit helps. Oct 21, 2014 at 8:04

So normally I would consider a "column" of expressions to be of the form:

col0={{"a"}, {"b"}, {"c"}, {"d"}}


Note that Mathematica uses Row Major order.

row0=First[Transpose[col0]]


would extract the first column into a row list.

As previously mentioned, appending to lists with AppendTo in a do loop can be expensive. Avoid if possible. Consider using Table instead.

col1=Table[FromCharacterCode[{{iChr}}], {iChr, 97, 100, 1}]
row1=Table[FromCharacterCode@iChr, {iChr, 97, 100, 1}]


If the code in your Do loop is lengthy, you can address this by putting it into a module, and then calling that module from the Table command. (i.e. Replace FromCharacterCode in the toy example with a function call to your module.)