0

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
  • 1
    It's the *exact same* reason. The *type* of the object is irrelevant. Mutable/immutable objects don't behave differently with regards to the semantics of assignment – juanpa.arrivillaga Nov 28 '20 at 04:12
  • Thank you Juanpa for your reply but I am still unable to connect the dots. According to https://stackoverflow.com/questions/2347265/why-does-behave-unexpectedly-on-lists, += on lists is an in-place operation. For instance, `a=[0]; a+=[1]` would not change the result of `id(a)`. – Shihong Zhu Nov 29 '20 at 03:15
  • 1
    Right, that's irrelevant. Completely irrelevant. The only relevant fact is that `+=` *assigns to a name*. Since it is an assignment, the compiler marks it as a local variable. The *type* of the object being referred to by the variable *does not matter in the slightest*. The fact that it is an in-place operation when the object is a `list` does not matter either. – juanpa.arrivillaga Nov 29 '20 at 03:29
  • I've added a second [duplicate target](https://stackoverflow.com/questions/9264763/dont-understand-why-unboundlocalerror-occurs-closure) that explains this better than the original, which sort of assumes you understand that. Also, this is a good external resource that explains it in more detail: https://eli.thegreenplace.net/2011/05/15/understanding-unboundlocalerror-in-python – juanpa.arrivillaga Nov 29 '20 at 03:31
  • Thanks a lot Juanpa. I got it now. That also clears my confusion on why this is called 'augmented assignment' as it is an assignment. – Shihong Zhu Nov 29 '20 at 04:43

0 Answers0