The command Do[Print[i], {i, 1, 3}] does what you expect: creates 3 output lines of 1, 2 and 3, in that order.

If one merges these output cells, then evaluates the original Do command, the output is now 3, then 2, then 1. When one deletes the output cells, the regular behavior returns.

It isn't that the Do loop is running backwards. When one does "the same thing" with

temp = {}
Do[AppendTo[temp, i];
Print[i], {i, 1, 3}];

the order of the Print command is reversed, but the contents of temp are still {1, 2, 3}, not {3, 2, 1}.

Why does this happen? Does Print write to a queue that is sometimes dumped in reverse order?

I am running Mathematica 11.0.0 on Windows 10

  • $\begingroup$ You can see how the printing order is affected by trying with Do[Pause[1]; Print[i], {i, 1, 3}]. $\endgroup$ – J. M. will be back soon Sep 25 '18 at 10:40
  • $\begingroup$ Forgot to add: running Mathematica 11.0.0 on Windows 10. $\endgroup$ – GregH Sep 25 '18 at 11:31
  • $\begingroup$ I can reproduce it in M11.3 on macOS. $\endgroup$ – Szabolcs Sep 25 '18 at 12:28
  • $\begingroup$ Me, too (after Szabolcs explained to me what to do...) $\endgroup$ – Henrik Schumacher Sep 25 '18 at 12:34

The reason this happens is described in ref/CellPrint, in the possible issues section:

Setting CellAutoOverwrite and GeneratedCell can cause unexpected results:

In[1]:= CellPrint[Cell["First", "Print", CellAutoOverwrite -> False, 
   GeneratedCell -> False]];

Out[2]= "Last"


Merging the cells sets these two options:

  • it is no longer a generated cell,
  • and, theoretically if the user merged the cells, the user doesn't want them overwritten.

Tricky behavior, but I think it is within the scope of what's documented. A solution to improve the behavior would probably be appreciated, but for now it seems documented and expected.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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