Modifying global Mutable Objects

Example 1: Modifying list elements without using global keyword.

Here, we can modify list elements defined in global scope without using global keyword. Because we are not modifying the object associated with the variable arr, but we are modifying the items the list contains. Since lists are mutable data structures, thus we can modify its contents.

Python3




arr = [10, 20, 30]
 
 
def fun():
    for i in range(len(arr)):
        arr[i] += 10
 
 
print("'arr' list before executing fun():", arr)
fun()
print("'arr' list after executing fun():", arr)


Output:

'arr' list before executing fun(): [10, 20, 30]
'arr' list after executing fun(): [20, 30, 40]

Example 2: Modifying list variable using global keyword.

Here we are trying to assign a new list to the global variable. Thus, we need to use the global keyword as a new object is created. Here, if we don’t use the global keyword, then a new local variable arr will be created with the new list elements. But the global variable arr will be unchanged. 

Python3




arr = [10, 20, 30]
 
 
def fun():
    global arr
    arr = [20, 30, 40]
 
 
print("'arr' list before executing fun():", arr)
fun()
print("'arr' list after executing fun():", arr)


Output:

'arr' list before executing fun(): [10, 20, 30]
'arr' list after executing fun(): [20, 30, 40]

Global keyword in Python

In this article, we will cover the global keyword, the basic rules for global keywords in Python, the difference between the local, and global variables, and examples of global keywords in Python.

Similar Reads

What is the purpose of global keywords in python?

A global keyword is a keyword that allows a user to modify a variable outside the current scope. It is used to create global variables in Python from a non-global scope, i.e. inside a function. Global keyword is used inside a function only when we want to do assignments or when we want to change a variable. Global is not needed for printing and accessing....

Global keyword in the python example

Example 1: Accessing global Variable From Inside a Function...

Modifying global Mutable Objects

...

Global variables across Python modules

...

Global in Nested functions

...

Contact Us