Iteration using range() in Python - Time & Space 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.
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 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.
As n grows, the number of print actions grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 prints |
| 100 | 100 prints |
| 1000 | 1000 prints |
Pattern observation: If you double n, the work doubles too. The growth is steady and direct.
Time Complexity: O(n)
This means the time needed grows in a straight line with the size of n.
[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.
Understanding how simple loops grow with input size is a key skill. It helps you explain how your code behaves when handling more data.
"What if we changed range(n) to range(0, n, 2)? How would the time complexity change?"