print() function basics in Python - Time & Space Complexity
Let's see how the time to run a program changes when we use the print() function.
We want to know how the number of print statements affects the time it takes to run.
Analyze the time complexity of the following code snippet.
for i in range(n):
print(i)
This code prints numbers from 0 up to n-1, one by one.
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 gets bigger, 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 number of print calls grows directly with n.
Time Complexity: O(n)
This means the time to run grows in a straight line as the number of print statements increases.
[X] Wrong: "print() runs instantly and does not affect time as n grows."
[OK] Correct: Each print takes some time, so more prints mean more total time.
Understanding how simple commands like print() add up helps you think clearly about program speed in real tasks.
"What if we printed only every other number instead of every number? How would the time complexity change?"