Nonlocal keyword in Python - Time & Space 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.
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 the loops, recursion, array traversals that repeat.
- Primary operation: The
forloop insideinner()that runsntimes. - How many times: Exactly once per call to
outer(n), but the loop runsntimes.
As n grows, the loop runs more times, so the work grows in a straight line with n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 steps |
| 100 | 100 steps |
| 1000 | 1000 steps |
Pattern observation: Doubling n doubles the work done.
Time Complexity: O(n)
This means the time it takes grows directly with the size of the input n.
[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.
Understanding how nested functions and variable scopes affect performance helps you write clear and efficient code, a skill valued in many coding challenges.
What if we removed the nonlocal keyword and instead returned the count from inner()? How would the time complexity change?