This is a follow up question to UnboundLocalError on local variable when reassigned after first use.
case-1, the following code
a = 0
def test_immutable():
a += 1
test_immutable()
encounters an error:
UnboundLocalError: local variable 'a' referenced before assignment
Answers to the original post explains the first case well. a += 1
makes an assignment, and so makes a
a local variable that has not been assigned with any object yet, and therefore referencing it causes the UnboundLocalError
.
When I replace a
with array[0]
in the second example below, it works without UnboundLocalError
.
case-2, the following code
array = [0, 0, 0]
def test_mutable():
array[0] += 1
test_mutable()
print(array)
outputs
[1, 0, 0]
I guess it has something to do with a
being immutable while array
being mutable. But how exactly does Python treat the two cases differently? I'm confused.