Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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 Pickett, Sjoerd C. de Vries, Artes, Yves Klett, Mr.Wizard Oct 6 '13 at 19:31

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

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

1 Answer 1

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. –  Pickett Oct 6 '13 at 18:21

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