-3

I want to print a list, perform some operations and print again, flushing the list.

a=[1,2,3,4,5,6,7,8,9]

for i in range (0, 10):
    a.append(i)
    a=a[-5:]
    print(*a, sep='\n')

I expect the list to be cleared from the screen and the new one takes its place, buy I don't know how to to that.

Prune
  • 76,765
  • 14
  • 60
  • 81
Frikeando
  • 1
  • 2
  • Your formatting seems to be odd. But, issue seems to be related to the immutable nature of the lists. If you want to have a list with new values while keeping the old ones then create a new list from your existing list. – mad_ Jan 29 '19 at 19:09
  • Clearing the screen isn't something that can be universally done in the terminal. You can use `os.system('clear')`, or some VT100 codes to move the cursor up to the start of the list again, but it's not going to be trivial. – Draconis Jan 29 '19 at 19:12

2 Answers2

0

Try out the colorama package to enable ANSI escape sequences:

import colorama
import time
colorama.init()

a=[1,2,3,4,5,6,7,8,9]

for i in range (0, 10):
    a.append(i)
    a=a[-5:]
    print(*a, end='\r')
    time.sleep(0.5)

The '\r' character places the cursor back at the beginning of the line, so you can "print over it".

Anakhand
  • 2,838
  • 1
  • 22
  • 50
0

If I get the point, try this:

import sys
import time

a=[1,2,3,4,5,6,7,8,9]
for i in range (0, 10):
  a.append(i)
  a=a[-5:]
  print(chr(27) + "[2J")
  print(*a, sep='\n', flush=True)
  time.sleep(0.5)
iGian
  • 11,023
  • 3
  • 21
  • 36