0

I want to print out various sizes of numpy arrays one after the other in a for loop, but removing the previous print at each step in the loop. A solution often suggested for strings that are less than 1 line long is the following:

import numpy as np
import time

for i in range(5):
    a = np.ones(i)
    print(a,end = '\r')
    time.sleep(0.5)

This works as the array fits on one line and thus the '\r' argument in the print function works fine, it goes back to the beginning of the line for the next print, so it prints [] then [1.] then [1. 1. ] then [1. 1. 1.] etc.

A problem occurs when the print is larger than one line, and with '\r' it just goes back to the penultimate line, like so:

for i in range(5):
    a = np.ones(shape = (i,i))
    print(a,end = '\r')
    time.sleep(0.5)

This gives the following:

[[1. 1.]
[[1. 1. 1.]
 [1. 1. 1.]
[[1. 1. 1. 1.]
 [1. 1. 1. 1.]
 [1. 1. 1. 1.]
 [1. 1. 1. 1.]]

whereas I would like the arrays to update in size without overlapping on the last line. Essentially, is there a way to replace end = '\r' with something else so that it goes back to the beginning of the whole print rather than just the beginning of the line? I am doing this in Jupyter notebook with Python 3.8.3

  • 1
    Clear the screen? `os.system('cls')` on Windows, else `os.system('clear')`. –  May 14 '21 at 15:25
  • @JustinEzequiel doesn't seem to work, same thing happens as described above. I'm using Jupyter notebook in case this changes something. – greeneyesfifa May 14 '21 at 18:41
  • 1
    Does this answer your question? [Rewrite multiple lines in the console](https://stackoverflow.com/questions/6840420/rewrite-multiple-lines-in-the-console) – Seb May 14 '21 at 18:47
  • "I'm using Jupyter notebook" -- you should have mentioned that at the start. –  May 14 '21 at 19:20
  • @Seb No, but this one did https://stackoverflow.com/questions/38540395/overwrite-previous-output-in-jupyter-notebook – greeneyesfifa May 14 '21 at 21:15

1 Answers1

0

After some more research, I found a solution. The key word in this was "Jupyter notebook" which allowed me to find this page:

Overwrite previous output in jupyter notebook

This uses Ipython.display and the solution to my question would be written as follows:

import numpy as np
import time
from IPython.display import clear_output

for i in range(5):
    clear_output(wait=True)
    a = np.ones(shape = (i,i))
    print(a)
    time.sleep(0.5)