s += i is just sugar for s = s + i . *
This means that you are assigning a new value to the s variable (instead of mutating it in place). When you assign a variable, Python assumes that it is local to this function. However, before assigning it needs to evaluate s + i , but s is local and still not assigned β Error.
In the second case, s[0] += i you never assign s directly, but only access the element from s . Thus, Python can clearly see that it is not a local variable and is looking for it in the outer scope.
Finally, a nicer alternative (in Python 3) is to explicitly say that s not a local variable:
def foo(n): s = n def bar(i): nonlocal s s += i return s return bar
(There is no need for s - you can just use n instead of bar ).)
* The situation is a little more complicated , but an important problem is that the calculations and assignment are performed in two separate steps.
source share