1
$\begingroup$

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?

$\endgroup$

closed as off-topic by Szabolcs, rhermans, Henrik Schumacher, mattiav27, AccidentalFourierTransform Jul 29 '18 at 13:26

This question appears to be off-topic. The users who voted to close gave this specific reason:

  • "This question arises due to a simple mistake such as a trivial syntax error, incorrect capitalization, spelling mistake, or other typographical error and is unlikely to help any future visitors, or else it is easily found in the documentation." – Szabolcs, rhermans, Henrik Schumacher, mattiav27, AccidentalFourierTransform
If this question can be reworded to fit the rules in the help center, please edit the question.

  • 2
    $\begingroup$ You're confusing Append and AppendTo. Please look them up. $\endgroup$ – Szabolcs Jul 29 '18 at 8:36
  • $\begingroup$ @Szabolcs would you object to me re-marking this as a duplicate of (112183)? $\endgroup$ – Mr.Wizard Jul 29 '18 at 14:41
8
$\begingroup$

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.

$\endgroup$

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