When you do x =
you're not modifying the object that x
references, you're just changing the reference x
to point to a different object, in this case, another int
. In this case it's event irrelevant whether x
points to an immutable object. If you would do x = x + [5]
with lists, it would also remain unchanged. Note the difference:
def b1(x = []):
x = x + [5]
print(x)
def b2(x = []):
x.append(5)
print(x)
print("b1:")
b1()
print("b1:")
b1()
print("b2:")
b2()
print("b2:")
b2()
Gives:
b1:
[5]
b1:
[5]
b2:
[5]
b2:
[5, 5]
When the function is being executed, you're working on a local variable x
that either was initialized using the default value, or provided by the caller. So what gets rebound is the local variable x
, not the default value for the parameter.
You may want to also read about the difference between formal and actual parameters. It's only slightly related to this problem, but may help you understand this better. An example explanation can be found here.