1

The following minimal non working example is an infinite loop: why is it so?

list={1};
n=2;
While[Last@list<10,Append[list,n];n++]

It seems that Append does not append the last value to list so While is always True, but why is it so?

mattiav27
  • 6,677
  • 3
  • 28
  • 64

1 Answers1

8

The loop is infinite, because the result of Append is the new list, not the modification of existing.

Documentation:

Append[expr,elem]
  gives expr with elem appended.

And:

AppendTo[s,elem]
  appends elem to the value of s, and resets s to the result.

So, you either need to reassign the value of Append or use AppendTo:

list={1};
n=2;
While[Last@list<10,list=Append[list,n];n++]

Or:

list={1};
n=2;
While[Last@list<10,AppendTo[list,n];n++]

Both will yield the same result.

m0nhawk
  • 3,867
  • 1
  • 20
  • 35