Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set your subtitle preferences in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please refer to our video player troubleshooting guide for assistance.

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.

00:17 So, how can you know whether it’s possible to modify a variable outside the function’s local scope? Well, a function can never modify an immutable variable outside its local scope,

00:34 and a function is able to modify a mutable variable outside its local scope in place.

00:44 Let’s start with an example that shows you it is not possible for a function to redefine the value of a variable that is already defined outside its scope.

00:58 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 x is 40, but when you look at the value of x itself, then you see that the value of x is still 20.

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.

02:06 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,

02:27 you will see that the contents of the list changed.

02:33 But if the function tries to replace the list entirely, then it will create a new object in the local scope and won’t modify the list that was created in the global scope.

02:46 So, after running f() and looking at my list, you will see that the list hasn’t changed at all.

02:57 But what if you really need to modify an immutable value in the global scope? We will have a look at that in the next lesson.

Become a Member to join the conversation.