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.