0
0
Pythonprogramming~5 mins

Nonlocal keyword in Python - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Nonlocal keyword
O(n)
Understanding Time Complexity

Let's explore how the nonlocal keyword affects the speed of a Python function.

We want to see how the number of steps changes as the input grows.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

def outer(n):
    count = 0
    def inner():
        nonlocal count
        for i in range(n):
            count += 1
    inner()
    return count

This code counts from 0 up to n using a nested function that changes a variable from the outer function.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The for loop inside inner() that runs n times.
  • How many times: Exactly once per call to outer(n), but the loop runs n times.
How Execution Grows With Input

As n grows, the loop runs more times, so the work grows in a straight line with n.

Input Size (n)Approx. Operations
1010 steps
100100 steps
10001000 steps

Pattern observation: Doubling n doubles the work done.

Final Time Complexity

Time Complexity: O(n)

This means the time it takes grows directly with the size of the input n.

Common Mistake

[X] Wrong: "Using nonlocal makes the function slower because it adds extra work."

[OK] Correct: The nonlocal keyword only changes where the variable lives; it does not add extra loops or steps. The main time cost is still the loop running n times.

Interview Connect

Understanding how nested functions and variable scopes affect performance helps you write clear and efficient code, a skill valued in many coding challenges.

Self-Check

What if we removed the nonlocal keyword and instead returned the count from inner()? How would the time complexity change?