Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

This question already has an answer here:

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?

share|improve this question

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… (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

share|improve this answer
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

Not the answer you're looking for? Browse other questions tagged or ask your own question.