0
0
Pythonprogramming~5 mins

print() function basics in Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: print() function basics
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

As n gets bigger, the number of print calls grows the same way.

Input Size (n)Approx. Operations
1010 print calls
100100 print calls
10001000 print calls

Pattern observation: The number of print calls grows directly with n.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line as the number of print statements increases.

Common Mistake

[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.

Interview Connect

Understanding how simple commands like print() add up helps you think clearly about program speed in real tasks.

Self-Check

"What if we printed only every other number instead of every number? How would the time complexity change?"