0
0
Pythonprogramming~5 mins

Try–except–else behavior in Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Try-except-else behavior
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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).
How Execution Grows With Input

Each item causes one try-except-else check, so work grows directly with input size.

Input Size (n)Approx. Operations
10About 10 try-except-else checks
100About 100 try-except-else checks
1000About 1000 try-except-else checks

Pattern observation: The total work grows in a straight line as input grows.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows directly in proportion to how many items we process.

Common Mistake

[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.

Interview Connect

Understanding how try-except-else affects time helps you explain error handling costs clearly and confidently in real coding situations.

Self-Check

"What if the except block contained a loop over all items? How would the time complexity change?"