For loop execution model in Python - Time & Space Complexity
When we use a for loop, we want to know how the time it takes grows as we repeat actions.
We ask: How does running the loop more times affect the total work done?
Analyze the time complexity of the following code snippet.
def print_numbers(n):
for i in range(n):
print(i)
This code prints numbers from 0 up to n-1 using a for loop.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The print statement inside the for loop.
- How many times: Exactly n times, once for each number from 0 to n-1.
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: The work grows directly in step with n; double n means double work.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of loop steps.
[X] Wrong: "The loop runs instantly no matter how big n is."
[OK] Correct: Each loop step takes some time, so more steps mean more total time.
Understanding how loops grow helps you explain your code clearly and shows you know how programs scale.
"What if we added a nested for loop inside the first one? How would the time complexity change?"