this is a follow up question to Variable scope, immutable vs mutable, in terms of +=.
def update():
L.extend([1])
L=[1,2,3]
update()
print(L)
outputs [1,2,3,1]
but
def update1():
L=L+[1]
L=[1,2,3]
update1()
print(L)
outputs UnboundLocalError: local variable 'L' referenced before assignment
but
def update2():
L[0]=L[0]+1
L=[1,2,3]
update2()
print(L)
outputs [2,2,3]
i understand that update1()
produces an UnboundLocalError because, when an assignment to L is made inside update1()
, python marks L as a local variable with no assigned value. so L+=[1]
gives an error, since a variable is being read before being assigned.(And this is also why "you cannot modify a variable defined outside the current scope")
And i understand that update()
works because no assignment to L was made, so python did not create a local variable L( with no assigned value). hence, according to the LEGB rule, the extend method is then applied to global variable L.
But i do not understand why update2()
works.
I was thinking that one or all of the following things could happen
- python can give a syntax error, or maybe a type
error()
(sinceL[0]
is not a valid variable name) - python can give a type error, if L gets marked as a local variable with no assigned value.
UnboundedLocalError
but it is none of the above
Should it (update2()
) be considered as an exception, or is there an explanation behind why update(2)
works the way it does?