print() parameters and formatting in Python - Time & Space Complexity
We want to understand how the time it takes to run print() changes when we use different parameters and formatting.
How does the number of items or formatting affect the time print() needs?
Analyze the time complexity of the following code snippet.
for i in range(n):
print(f"Number: {i}", end=' ', flush=False)
print()
This code prints numbers from 0 to n-1 on the same line with a space, then moves to a new line.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The print() function inside the loop.
- How many times: It runs once for each number from 0 to n-1, so n times.
As n grows, the number of print calls grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 print calls |
| 100 | 100 print calls |
| 1000 | 1000 print calls |
Pattern observation: The time grows directly with the number of items printed.
Time Complexity: O(n)
This means the time to print grows in a straight line as you print more items.
[X] Wrong: "Changing print formatting or parameters does not affect time complexity at all."
[OK] Correct: While formatting itself is fast, more complex formatting or flushing output can add small extra time per print, but the main time still grows with how many times print runs.
Understanding how print and formatting scale helps you think about how programs handle output efficiently, a useful skill for writing clear and fast code.
"What if we added flush=True inside the print call? How would the time complexity change?"