0
0
Pythonprogramming~5 mins

Iteration using range() in Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Iteration using range()
O(n)
Understanding Time Complexity

When we use range() to repeat actions, it is important to know how the time needed grows as the number of repeats increases.

We want to understand how the work changes when the range gets bigger.

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, repeating the print action n times.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The print(i) inside the loop.
  • How many times: Exactly once for each number from 0 to n-1, so n times.
How Execution Grows With Input

As n grows, the number of print actions grows the same way.

Input Size (n)Approx. Operations
1010 prints
100100 prints
10001000 prints

Pattern observation: If you double n, the work doubles too. The growth is steady and direct.

Final Time Complexity

Time Complexity: O(n)

This means the time needed grows in a straight line with the size of n.

Common Mistake

[X] Wrong: "The loop runs instantly because it just counts numbers."

[OK] Correct: Even counting and printing each number takes time, so the total time grows with n.

Interview Connect

Understanding how simple loops grow with input size is a key skill. It helps you explain how your code behaves when handling more data.

Self-Check

"What if we changed range(n) to range(0, n, 2)? How would the time complexity change?"