global keyword is used to access and modify a global variable from inside a function. Without using global, assigning a value to a variable inside a function creates a new local variable instead.
x = 10
def update():
global x
x = 20
update()
print(x)
Output
20
Explanation: statement global x refers to the global variable x inside the function. After x is updated to 20, the change is reflected outside the function.
Syntax
global variable_name
Parameter: variable_name - name of the global variable that will be accessed or modified inside the function.
Examples
Example 1: Here, we access a global variable inside a function and print its value.
message = "Welcome"
def show():
print(message)
show()
Output
Welcome
Explanation: variable message is defined outside the function, making it a global variable. Since the function only reads its value, the global keyword is not required.
Example 2: Here, we try to modify a global variable without using the global keyword.
count = 10
def update():
count = count + 5
print(count)
update()
Output
ERROR!
Traceback (most recent call last):
File "<main.py>", line 7, in <module>
File "<main.py>", line 4, in update
UnboundLocalError: cannot access local variable 'count' where it is not associated with a value
Explanation: assignment count = count + 5 makes count a local variable. Since the local variable is used before it is assigned a value, Python raises an UnboundLocalError.
Example 3: Here, we update a global variable inside a function using the global keyword.
count = 10
def update():
global count
count = count + 5
update()
print(count)
Output
15
Explanation: statement global count refers to the global variable count. After executing count = count + 5, the updated value is reflected outside the function.
Working with Mutable Objects
Mutable objects, such as lists and dictionaries, can have their contents modified without using the global keyword. However, if you assign a new object to the variable, the global keyword is required.
Example 1: Here, we update the elements of a global list inside a function.
numbers = [10, 20, 30]
def update():
for i in range(len(numbers)):
numbers[i] += 10
print("Before:", numbers)
update()
print("After:", numbers)
Output
Before: [10, 20, 30] After: [20, 30, 40]
Explanation: function modifies the existing elements of the list numbers. Since the list itself is not reassigned, the global keyword is not required.
Example 2: Here, we replace the entire list inside a function using the global keyword.
numbers = [10, 20, 30]
def update():
global numbers
numbers = [20, 30, 40]
print("Before:", numbers)
update()
print("After:", numbers)
Output
Before: [10, 20, 30] After: [20, 30, 40]
Explanation: statement global numbers refers to the global variable numbers. It allows the function to assign a new list to the variable, and the updated list is reflected outside the function.