I read in many places that +=
is an in-place operation, which does not create a new list. Given this, I would expect the inner function to be able to see and mutate the lst
defined in outer()
. Could someone explain what is going on here? I understand there are alternative ways to make it work as expected like lst.append(2)
. I am just trying to understand why it does NOT work.
There is a similar question regarding +=
on integers UnboundLocalError with nested function scopes
That question is easy to answer as integers are immutable so ctr += 1
actually declares a new name in the inner function, and that new name is referenced before a value is assigned. This argument does not apply to the case here since +=
on a list does not create new bindings.
def outer():
lst = [0]
def inner():
lst += [2]
inner()
outer()
UnboundLocalError: local variable 'lst' referenced before assignment