Modifying Variables Out of Scope
00:00 When you want to modify variables, then you need to be aware of the scope that the variable you need to modify is in. Sometimes, a function is able to modify a variable outside of its local scope, and sometimes it is not.
This module declares a variable called
x and it assigns a value
20. Then inside the function
f(), the function declares another variable
x to a value
40, after which it prints
x. Now, when you load the module and call the function
f(), you will see that the value of
40, but when you look at the value of
x itself, then you see that the value of
x is still
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.
In this example, a list—which is a mutable object—is created in the global scope. And the first item of this list is replaced with another value in the function
f(). After running
f() and looking at my list,
Become a Member to join the conversation.