Continue statement behavior in Python - Time & Space Complexity
Let's explore how the continue statement affects the time complexity of loops.
We want to know how skipping some steps changes the total work done as input grows.
Analyze the time complexity of the following code snippet.
for i in range(n):
if i % 2 == 0:
continue
print(i)
This code loops from 0 to n-1, but skips printing when the number is even.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The loop runs through all numbers from 0 to n-1.
- How many times: Exactly n times, but some steps skip printing due to
continue.
Even though some steps skip printing, the loop still checks every number.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks, 5 prints |
| 100 | 100 checks, 50 prints |
| 1000 | 1000 checks, 500 prints |
Pattern observation: The loop runs n times, but printing happens about half as often.
Time Complexity: O(n)
This means the total work grows directly with the size of the input, even if some steps skip actions.
[X] Wrong: "Since continue skips some steps, the loop runs fewer times and is faster."
[OK] Correct: The loop still checks every item; skipping only avoids some actions inside the loop, not the loop itself.
Understanding how continue affects loops helps you explain code efficiency clearly and shows you know how loops behave in real situations.
What if we replaced continue with break? How would the time complexity change?