Try–except–else behavior in Python - Time & Space Complexity
We want to understand how the time it takes to run a try-except-else block changes as the input changes.
Specifically, we ask: how often does the code inside each part run as input grows?
Analyze the time complexity of the following code snippet.
def process_items(items):
for item in items:
try:
result = 10 / item
except ZeroDivisionError:
result = 0
else:
result += 1
return result
This code tries to divide 10 by each item, handles division by zero, and adds 1 if no error occurs.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop runs once for each item in the list.
- How many times: Exactly as many times as there are items (n times).
Each item causes one try-except-else check, so work grows directly with input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 try-except-else checks |
| 100 | About 100 try-except-else checks |
| 1000 | About 1000 try-except-else checks |
Pattern observation: The total work grows in a straight line as input grows.
Time Complexity: O(n)
This means the time to run grows directly in proportion to how many items we process.
[X] Wrong: "The except block makes the code slower for all items, so time grows faster than input size."
[OK] Correct: The except block only runs when an error happens, so most items just run the try and else parts once each. The overall time still grows linearly.
Understanding how try-except-else affects time helps you explain error handling costs clearly and confidently in real coding situations.
"What if the except block contained a loop over all items? How would the time complexity change?"