Python Forum

Full Version: Why does this work and this doesnt=
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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!!
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.