0

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?

physicsGuy
  • 557
  • 3
  • 9
  • You're looking for AppendTo. Append doesn't modify the value of plotVals. Also take a look at ConstantArray. – C. E. Oct 06 '13 at 17:20
  • 2
    check http://mathematica.stackexchange.com/questions/18393/what-are-the-most-common-pitfalls-awaiting-new-users/19804#19804 (David Speyer's answer) – Pinguin Dirk Oct 06 '13 at 17:36

1 Answers1

0
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

Pankaj Sejwal
  • 2,063
  • 14
  • 23
  • 1
    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 06 '13 at 17:46
  • 1
    The second example uses linked lists, which you can read more about here. – C. E. Oct 06 '13 at 18:21