0

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.

yogeshagr
  • 819
  • 2
  • 11
  • 20
  • variable = "this is a string" def function(): global variable variable = "this is a new string" return print variable function() print variable In the above code, I am able to modify the global string. – yogeshagr Jan 06 '16 at 10:26
  • If you read through the linked duplicate, you'll find that it is extremely thorough. – TigerhawkT3 Jan 06 '16 at 10:45
  • @TigerhawkT3 Okay thank you, now I am able to understand the concepts better. – yogeshagr Jan 06 '16 at 10:54

0 Answers0