Python Forum
Why does this work and this doesnt= - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Why does this work and this doesnt= (/thread-10458.html)



Why does this work and this doesnt= - puruvaish24 - May-22-2018

x = [0,0]
print(x)
def incrment():
  x[0] = 1
  x[1] = 2
incrment()
print(x)

y = [0,0]
print(y)
def increment():
  y = [1,2]
increment()
print(y)
why does the first code work and the second doesnt!!


RE: Why does this work and this doesnt= - scidam - May-22-2018

Everything works fine! In case of x-variable 'incrementation', when you call increment(), x[0] = 1 uses x-object from outer scope, exactly, x[0]=1 is equivalent for x.__setitem__(0, 1), but there is no x-object in the increment function, so, x.__setitem__(0, 1) uses x-object from global/outer scope, and x (from outer scope) becomes equal to [1,2]

In case of y variable you perform assignment y=[1,2], this lead to creation of local variable y, that is visible only inside the increment function. Therefore, y-variable from global/outer scope doesn't change.