In python to modify a global variable inside a function, we need to declare it as a global "variable" inside the function. Example1:
variable = [10]
def function():
global variable
variable = [20]
return
print variable # will print [10]
function()
print variable # will print [20]
Without global it will treat the variable as a local variable and will not modify global variable. Exmaple2:
variable = [10]
def function():
variable = [20]
return
print variable # will print [10]
function()
print variable # will print [10]
However I came across a situation where I need to modify a global list. But what struck my mind is that I am able to modify global list using "append" function of list object. I have not declared variable as global inside the function. Example3:
variable = [10]
def function():
variable.append(20)
return
print variable # will print [10]
function()
print variable # will print [10, 20]
My doubt is how does "append" function of list object, modifies the global variable, without having access to global variable ? If someone has explanation of this behaviour please let me know.