Python
programming
print-statement
coding
code-efficiency

Print in one line dynamically

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

Dynamic single-line printing in Python means updating text on the same console line instead of printing a new line each time. This is commonly used for progress bars, countdown timers, loading spinners, and download indicators. Python's print() function supports this through the end and flush parameters, and the \r carriage return character moves the cursor back to the beginning of the line so the next print overwrites the previous output.

Using print() with end and flush

python
1import time
2
3# Print a countdown on one line
4for i in range(10, 0, -1):
5    print(f"\rCountdown: {i} ", end="", flush=True)
6    time.sleep(1)
7print("\rCountdown: Done!")
8
9# How it works:
10# \r      — carriage return, moves cursor to start of line
11# end=""  — prevents the default newline after print
12# flush=True — forces immediate output (bypasses buffering)

By default, print() appends a newline (\n) and Python buffers stdout. Setting end="" removes the newline, \r returns the cursor to the start of the line, and flush=True ensures the text appears immediately.

Progress Bar Example

python
1import time
2
3total = 50
4for i in range(total + 1):
5    percent = i * 100 // total
6    bar = "█" * (i * 40 // total) + "-" * (40 - i * 40 // total)
7    print(f"\r[{bar}] {percent}%", end="", flush=True)
8    time.sleep(0.05)
9print()  # move to next line when done

This creates a visual progress bar that updates in place. The print() at the end ensures the cursor moves to a new line after the bar reaches 100%.

Using sys.stdout.write

python
1import sys
2import time
3
4for i in range(1, 11):
5    sys.stdout.write(f"\rProcessing item {i}/10")
6    sys.stdout.flush()
7    time.sleep(0.5)
8sys.stdout.write("\n")

sys.stdout.write() gives lower-level control. Unlike print(), it does not add a newline or spaces, so you manage formatting entirely. Call sys.stdout.flush() explicitly to push buffered output to the terminal.

Printing Multiple Values on One Line

python
1# Use end=" " to print items separated by spaces on one line
2for i in range(10):
3    print(i, end=" ", flush=True)
4# Output: 0 1 2 3 4 5 6 7 8 9
5
6print()  # newline at the end
7
8# Using sep to control separator in a single print call
9print(1, 2, 3, 4, 5, sep=" -> ")
10# Output: 1 -> 2 -> 3 -> 4 -> 5
11
12# Join a list into one line
13items = ["apple", "banana", "cherry"]
14print(", ".join(items))
15# Output: apple, banana, cherry

Overwriting Longer Lines with Shorter Text

python
1import time
2
3messages = ["Downloading...", "Almost done", "Done!"]
4for msg in messages:
5    # Pad with spaces to overwrite leftover characters from longer text
6    print(f"\r{msg:<30}", end="", flush=True)
7    time.sleep(1)
8print()

When a shorter string replaces a longer one, leftover characters from the previous output remain visible. Use string formatting like {msg:<30} to pad the output with spaces, ensuring the entire previous line is overwritten.

ANSI Escape Codes for Advanced Control

python
1import time
2
3# Clear the entire line before writing
4CLEAR_LINE = "\033[2K"
5
6for i in range(5):
7    print(f"{CLEAR_LINE}\rStep {i + 1}/5: Processing...", end="", flush=True)
8    time.sleep(1)
9print(f"{CLEAR_LINE}\rAll steps complete.")

\033[2K is an ANSI escape code that clears the current line. This is more robust than padding with spaces and works in most modern terminals.

Common Pitfalls

  • Forgetting flush=True: Python buffers stdout by default. Without flush=True, the output may not appear until the buffer fills or a newline is printed, making the dynamic update invisible until the loop finishes.
  • Not using \r to return the cursor: Using end="" alone appends text to the same line without overwriting. You need \r at the start of the string to move the cursor back to the beginning so subsequent prints replace the previous text.
  • Shorter text leaving residual characters: If the new output is shorter than the previous one, old characters remain on screen. Pad the output with spaces (e.g., f"\r{msg:<40}") or use ANSI clear-line codes to prevent visual artifacts.
  • Using print() in Jupyter notebooks or IDEs: Some environments like Jupyter notebooks do not support \r properly. In Jupyter, use IPython.display.clear_output(wait=True) or display() with update for dynamic output.
  • Mixing print() with sys.stdout.write(): Both write to stdout but handle buffering and newlines differently. Mixing them can cause output ordering issues. Stick to one approach within a given output sequence.

Summary

  • Use print(text, end="", flush=True) with \r to overwrite the current line dynamically
  • \r moves the cursor to the start of the line; end="" prevents a newline; flush=True forces immediate output
  • sys.stdout.write() provides lower-level control without automatic newlines
  • Pad shorter output with spaces or use ANSI escape codes to clear residual characters
  • Use print(items, end=" ") or ", ".join(list) to print multiple values on one line
  • In Jupyter notebooks, use clear_output(wait=True) instead of \r

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.