# Do loop - variable does not change [duplicate]

I got the follwing code which should add a '1' 100 times to an empty list.

plotVals = {}
Do[Append[plotVals, 1], {l, 1, Nmax}];


The output is again an empty list, why is this the case?

-

## marked as duplicate by C. E., Sjoerd C. de Vries, Artes, Yves Klett, Mr.Wizard♦Oct 6 '13 at 19:31

This question was marked as an exact duplicate of an existing question.

You're looking for AppendTo. Append doesn't modify the value of plotVals. Also take a look at ConstantArray. – C. E. Oct 6 '13 at 17:20
check mathematica.stackexchange.com/questions/18393/… (David Speyer's answer) – Pinguin Dirk Oct 6 '13 at 17:36

Block[{plotVals = {}},
Do[{plotVals = Append[plotVals, 1], Print[plotVals]}, {l, 1, 5}]]


You will lose information if you simply use Append, so you need to store it.

{1} {1,1} {1,1,1}....

Also, Append/AppendTo is suicidal for speed, so rather use dynamically created list as,

Block[{plotVals = {}}, {Do[{plotVals = {plotVals, 1}}, {l, 1,
5}]}; plotVals]


{{{{{{}, 1}, 1}, 1}, 1}, 1}

Which you can flatten. It will give a much better performance than Append/AppendTo

-
A small side note: Almost all built-in Mathematica functions are functional - not imperative; that is, those don't cause side effects, but rather only produce a return value. Append is one of those for which it is somewhat non-obvious before you get used to it. Once you do grok the mostly-functional paradigm of Mathematica and tools it provides for it, you probably want to stay away from imperative constructs most of the time. – kirma Oct 6 '13 at 17:46
The second example uses linked lists, which you can read more about here. – C. E. Oct 6 '13 at 18:21