Nonlocal keyword in Python - Time & Space Complexity
Start learning this pattern below
Jump into concepts and practice - no test required
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?
Practice
nonlocal keyword do in Python?Solution
Step 1: Understand variable scopes
Variables inside a function are local by default, and inner functions cannot change outer variables unless specified.Step 2: Role of
Thenonlocalnonlocalkeyword allows the inner function to access and modify variables from the nearest enclosing function scope.Final Answer:
Allows an inner function to modify a variable from its outer function. -> Option BQuick Check:
nonlocal changes outer function variable = A [OK]
- Confusing nonlocal with global keyword
- Thinking nonlocal creates new variables
- Assuming nonlocal works outside functions
nonlocal inside a nested function?Solution
Step 1: Recall the syntax for nonlocal
The keywordnonlocalis followed by the variable name to indicate it refers to an outer function's variable.Step 2: Compare options
Only nonlocal variable_name uses the correct keyword and syntax:nonlocal variable_name.Final Answer:
nonlocal variable_name -> Option DQuick Check:
Correct nonlocal syntax = C [OK]
- Using 'global' instead of 'nonlocal'
- Writing 'local' or 'outer' which are invalid keywords
- Forgetting to write variable name after nonlocal
def outer():
x = 5
def inner():
nonlocal x
x = 10
inner()
return x
print(outer())Solution
Step 1: Trace variable assignment
Variablexis set to 5 inouter(). The inner function declaresnonlocal xand setsx = 10.Step 2: Effect of nonlocal on
Thexnonlocalkeyword allowsinner()to modifyxinouter(). So after callinginner(),xbecomes 10.Final Answer:
10 -> Option AQuick Check:
nonlocal changes outer x to 10 = D [OK]
- Thinking x remains 5 because inner is separate
- Expecting a syntax error for nonlocal usage
- Assuming inner creates a new local x
def counter():
count = 0
def increment():
count = count + 1
return count
return increment()
print(counter())Solution
Step 1: Identify variable scope issue
Insideincrement(),count = count + 1tries to read and writecount. Withoutnonlocal, Python treatscountas local, but it is used before assignment.Step 2: Fix with
Addingnonlocalnonlocal counttells Python to use thecountfromcounter(), allowing modification.Final Answer:
Missing 'nonlocal count' inside increment() -> Option CQuick Check:
Modify outer variable needs nonlocal = A [OK]
- Using global instead of nonlocal
- Ignoring variable scope causing UnboundLocalError
- Returning count without incrementing properly
def make_accumulator():
total = 0
def add(value):
nonlocal total
total += value
return total
return add
acc = make_accumulator()
print(acc(5))
print(acc(3))
print(acc(-2))What is the output of this code?
Solution
Step 1: Understand closure with nonlocal
The functionmake_accumulator()returnsadd, which rememberstotal. Thenonlocal totalletsaddupdatetotaleach call.Step 2: Trace calls to
First call: total=0+5=5, prints 5.acc
Second call: total=5+3=8, prints 8.
Third call: total=8+(-2)=6, prints 6.Final Answer:
5 8 6 -> Option AQuick Check:
Accumulator sums values using nonlocal total = B [OK]
- Expecting total to reset each call
- Confusing nonlocal with global
- Thinking output is separate values, not cumulative
