On Python 3, use the nonlocal keyword:

The nonlocal statement causes the listed identifiers to refer to previously bound variables in the nearest enclosing scope excluding globals. This is important because the default behavior for binding is to search the local namespace first. The statement allows encapsulated code to rebind variables outside of the local scope besides the global (module) scope.

def foo():
    a = 1
    def bar():
        nonlocal a
        a = 2
    bar()
    print(a)  # Output: 2

On Python 2, use a mutable object (like a list, or dict) and mutate the value instead of reassigning a variable:

def foo():
    a = []
    def bar():
        a.append(1)
    bar()
    bar()
    print a

foo()

Outputs:

[1, 1]
Answer from Adam Wagner on Stack Overflow
๐ŸŒ
Real Python
realpython.com โ€บ lessons โ€บ modify-variable-scope
Modifying Variables Out of Scope (Video) โ€“ Real Python
01:35 That is because when this assignment is executed, a new local reference to an integer object whose value is 40 is declared in the local namespace of the function f() and the value of x in the global namespace is not affected at all. Out of scope objects of a mutable type, on the other hand, can be modified in place.
Published: March 2, 2021
Discussions

Is it possible to modify variable in python that is in outer, but not global, scope? - Stack Overflow
Is it possible to modify b variable from within B() function? Surely I can read it from here and print(), but how to modify it? ... You can as long as b is mutable. An assignment to b will mask the outer scope. ... It's one of Python's embarrassments that nonlocal hasn't been backported to 2.x. More on stackoverflow.com
๐ŸŒ stackoverflow.com
February 11, 2014
What is the better way to change a variable from outside a function in a function?
What are you actually trying to do? What is the end goal? Use of globals should be as minimal as possible, and def not a go-to solution. Functions should be as idompotent as possible, and if they ever change an external value they should really be part of a class, changing an attribute. Take the list in as a parameter, modify the list, then return it is my suggestion. More on reddit.com
๐ŸŒ r/learnpython
19
0
February 28, 2025
Creating or modify function variable from outer scope python - Stack Overflow
My hope was that after setting ... agg() a variable will be defined. Can someone please explain what am I missing? why a is not added to the function scope dynamically ยท p.s. when I used dir(egg) I could see a was add the the function dict ... To put it simply: you can't and neither you should. If you want modifiable variable make ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
scopes in nested functions
See here for how to format code on reddit: https://www.reddit.com/r/learnpython/wiki/faq#wiki_how_do_i_format_code.3F It is impossible to read your code without proper formatting, but this demonstrates how variables are found multiple levels of nesting: def foo(): """Outer Function.""" x = 10 y = 10 def nested(): """Function nested in foo().""" y = 100 def nested_in_nested(): """Function nested in nested().""" nonlocal x nonlocal y # Search 'up' the levels for x and y. print(f'In nested_in_nested(): {x=} {y=}') # Modify x and y x += 1 y += 1 # Cannot modify y # Call nested_in_nested() from inside nested(). nested_in_nested() print(f'In nested(): {x=} {y=}') # Call nested() from inside foo(). nested() print(f'In foo(): {x=} {y=}') x = 1 # Global foo() Which prints: In nested_in_nested(): x=10 y=100 In nested(): x=11 y=101 In foo(): x=11 y=10 In the first printed line: In nested_in_nested(), the variable y is found in nested(), so y=100 is printed. It is then incremented. The variable x is not found in nested(), so Python looks next in the enclosing function foo() and finds x there. x=10 is printed. It is then incremented The nonlocal keyword allows a function to modify variables from the nearest enclosing scope that is not global. y in the outer function foo() is not modified by y = 100 in nested() because y in nested() is local to nested(). In the second printed line, notice that 'y' from the local scope of nested() has been incremented to 101, and x from the outer scope foo() has been incremented to 11. In the third printed line, the local x has been incremented The local y has not been incremented because that was not the instance of y accessed by y += 1 in nested_in_nested(). DO NOT WRITE CODE LIKE THIS. Python emphasises readability and this kind of code is horrible to read. More on reddit.com
๐ŸŒ r/learnpython
5
2
May 22, 2024
People also ask

Can nested functions modify global variables
ANS: Yes, nested functions can modify global variables by using the global keyword. However, this affects the module-level scope and is generally not the preferred way to modify variables in an enclosing functionโ€™s scope.
๐ŸŒ
sqlpey.com
sqlpey.com โ€บ python โ€บ python-nested-functions-modify-outer-scope
Python Nested Functions Modify Outer Scope Variable Solutions
How can an inner function change a variable from its parent function in Python
ANS: In Python 3, you can use the nonlocal keyword. For older versions or alternative approaches, you can use mutable objects like lists, pass variables explicitly as arguments, or use classes to manage state.
๐ŸŒ
sqlpey.com
sqlpey.com โ€บ python โ€บ python-nested-functions-modify-outer-scope
Python Nested Functions Modify Outer Scope Variable Solutions
What are the advantages of using a class to manage scope for nested functions
ANS: Using a class provides a structured way to encapsulate state. It keeps related variables together as attributes of an object, making it easier to manage, pass around, and modify by nested functions without relying on implicit scope rules.
๐ŸŒ
sqlpey.com
sqlpey.com โ€บ python โ€บ python-nested-functions-modify-outer-scope
Python Nested Functions Modify Outer Scope Variable Solutions
๐ŸŒ
Wordpress
unspecified.wordpress.com โ€บ 2008 โ€บ 06 โ€บ 27 โ€บ py3k-nonlocal
Py3K: Solving the โ€œouter scopeโ€ problem | Unspecified Behaviour
July 1, 2008 - I would like for inner_write to ... simple: Have a keyword like global, but rather than going all the way to the top scope, it just tells Python to look for the innermost scope with a bound variable of that name....
๐ŸŒ
Medium
martinxpn.medium.com โ€บ python-variable-scope-30-100-days-of-python-c7f74c46c0a5
Python Variable Scope (30/100 Days of Python) | by Martin Mirakyan | Medium
April 10, 2023 - Within the inner_function, we use the nonlocal keyword to access and modify the variable x in the outer local scope.
๐ŸŒ
Readthedocs
python-textbok.readthedocs.io โ€บ en โ€บ 1.0 โ€บ Variables_and_Scope.html
Variables and scope โ€” Object-Oriented Programming in Python 1 documentation
There is also a nonlocal keyword in Python โ€“ when we nest a function inside another function, it allows us to modify a variable in the outer function from inside the inner function (or, if the function is nested multiple times, a variable in one of the outer functions).
๐ŸŒ
Learn By Example
learnbyexample.org โ€บ python-variables-scope
Python Variables Scope - Learn By Example
April 20, 2020 - It allows you to assign to variables in an outer, but no-global, scope. Hereโ€™s an example that tries to reassign enclosing (outer) functionโ€™s local variable inside a nested (inner) function. # enclosing function def f1(): x = 42 # nested function def f2(): x = 0 print(x) # x is 0 f2() print(x) # x is still 42 f1() Here, the value of existing variable x didnโ€™t change. Because Python created a new local variable named x that shadows the variable in the outer scope.
Find elsewhere
๐ŸŒ
sqlpey
sqlpey.com โ€บ python โ€บ python-nested-functions-modify-outer-scope
Python Nested Functions Modify Outer Scope Variable Solutions
July 25, 2025 - Introduced in Python 3, the nonlocal keyword provides a direct and clean way to indicate that a variable assignment within a nested function should refer to a variable in the nearest enclosing scope, excluding the global scope. How it works: The nonlocal statement explicitly binds identifiers to variables in the closest enclosing functionโ€™s scope. This prevents the creation of a new local variable and ensures that the modification targets the intended outer variable.
๐ŸŒ
DNMTechs
dnmtechs.com โ€บ modifying-variables-in-outer-scopes-in-python-3
Modifying Variables in Outer Scopes in Python 3 โ€“ DNMTechs โ€“ Sharing and Storing Technology Knowledge
While local and global scopes provide a clear separation between variables, there are scenarios where we may want to modify a variable in an outer scope from within a nested function or block. Python allows us to achieve this by using the global keyword.
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ global-variable-in-python-non-local-python-variables
Global Variable in Python โ€“ Non-Local Python Variables
June 10, 2022 - You can change the scope of a local variable using the global keyword โ€“ which we'll discuss in the next section. The global keyword is mostly used for two reasons: To modify the value of a global variable.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ what is the better way to change a variable from outside a function in a function?
r/learnpython on Reddit: What is the better way to change a variable from outside a function in a function?
February 28, 2025 -

def generic_function(x, y):

x += 1

y += 1

x = 1

y = 2

generic_function(x, y)

print(x, y)

Above the variables x and y do not change because generic_function creates local variables x and y.

But I learned I could do that this way:

def generic_function():

list\[0\] += 1

list\[1\] += 1

list = [1, 2]

generic_function()

print(list[0], list[1])

A list can be used as parameters to the function, so the generic_function will modify the list that the name list refers to. And so no unwanted local variables are created.

But it seems strange to make your program search in a list for a value so many times, is there any other way to do it? Why couldn't I change which value the name x refers to directly?

๐ŸŒ
Python Tutorial
pythontutorial.net โ€บ home โ€บ advanced python โ€บ python nonlocal
Python nonlocal Scopes and nonlocal Variables
March 27, 2025 - Since Python doesnโ€™t find the ... the variable: To modify variables from a nonlocal scope in a local scope, you use the nonlocal keyword....
๐ŸŒ
YouTube
youtube.com โ€บ codehelp
How to modify outer scope of a function in python - YouTube
Download this code from https://codegive.com Certainly! Modifying the outer scope of a function in Python involves understanding the concept of closures and ...
Published: November 24, 2023
Views: 3
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ scopes in nested functions
r/learnpython on Reddit: scopes in nested functions
May 22, 2024 -

Is there a command like global or nonlocal with which I can make x=10 in my_nested_nested_function?
With global x it gets 1, with nonlocal it gets 100. If i comment the line where I set x to 100 in my_nested_function then the print statement puts out 10 (Which would be a workaround). But is there a way if I had to use the variable in my_nested_function?

x = 1
def my_function():
x = 10
def my_nested_function():
x = 100
def my_nested_nested_function():
nonlocal x
print(x)
my_nested_nested_function()
my_nested_function()
my_function()

Top answer
1 of 4
2
See here for how to format code on reddit: https://www.reddit.com/r/learnpython/wiki/faq#wiki_how_do_i_format_code.3F It is impossible to read your code without proper formatting, but this demonstrates how variables are found multiple levels of nesting: def foo(): """Outer Function.""" x = 10 y = 10 def nested(): """Function nested in foo().""" y = 100 def nested_in_nested(): """Function nested in nested().""" nonlocal x nonlocal y # Search 'up' the levels for x and y. print(f'In nested_in_nested(): {x=} {y=}') # Modify x and y x += 1 y += 1 # Cannot modify y # Call nested_in_nested() from inside nested(). nested_in_nested() print(f'In nested(): {x=} {y=}') # Call nested() from inside foo(). nested() print(f'In foo(): {x=} {y=}') x = 1 # Global foo() Which prints: In nested_in_nested(): x=10 y=100 In nested(): x=11 y=101 In foo(): x=11 y=10 In the first printed line: In nested_in_nested(), the variable y is found in nested(), so y=100 is printed. It is then incremented. The variable x is not found in nested(), so Python looks next in the enclosing function foo() and finds x there. x=10 is printed. It is then incremented The nonlocal keyword allows a function to modify variables from the nearest enclosing scope that is not global. y in the outer function foo() is not modified by y = 100 in nested() because y in nested() is local to nested(). In the second printed line, notice that 'y' from the local scope of nested() has been incremented to 101, and x from the outer scope foo() has been incremented to 11. In the third printed line, the local x has been incremented The local y has not been incremented because that was not the instance of y accessed by y += 1 in nested_in_nested(). DO NOT WRITE CODE LIKE THIS. Python emphasises readability and this kind of code is horrible to read.
2 of 4
2
Nested functions are best used when you need to repeat some code that only appears in your function. Since python's functions are closures, you can access variables from the outer scope just fine, which is handy. However, as soon as you want to modify one of those variables, you should think long and hard about whether this is the right way to do things. The keywords global and nonlocal are both good indications that you're doing something wrong. They are extremely rare in production code. This is for good reason, allowing variables to be modified outside of the scope they were defined in is a terrible idea and makes debugging so much more difficult when you accidentally set them to something wrong (and this will happen). You should also avoid reusing the same variable name when the previous variable is still visible. If there's one variable called x already available, do not create a new one inside a function with the same name. This also makes debugging errors harder, and can cause problems when you think you're referring to one variable, but it turns out you're actually referring to a different object that has the same name.
๐ŸŒ
w3tutorials
w3tutorials.net โ€บ blog โ€บ scope-of-variables-in-python-decorator
Python Decorator Variable Scope: Why Modifying Outer Variables Causes UnboundLocalError (And How to Fix It) โ€” w3tutorials.net
Pythonโ€™s LEGB rule determines variable scope; assignments trigger local variable treatment. Decorators use nested functions, which inherit enclosing scopes but require nonlocal to modify outer variables.
๐ŸŒ
Alma Better
almabetter.com โ€บ bytes โ€บ tutorials โ€บ python โ€บ python-variable-scope
Variable Scope in Python
February 16, 2024 - The nonlocal keyword declares a variable as nonlocal if defined outside the current scope. ... This code uses the nonlocal keyword to declare a variable as nonlocal (outside the current scope).