Python uses names to reference objects. When we say a = b
, a
and b
now refer to the same object, and if we change a
, we will see the same change in b
. For example:
a = [1, 2, 3]
b = a
a.append(4)
print(b)
will print [1, 2, 3, 4]
.
However, some operations do create new objects. For example:
a = 1
b = a
a = a + 1
print(b)
will print 1
. Clearly the line a = a + 1
somehow creates a new object with a value of a + 1
and binds the name a
to it. How does this work? What is the mechanism that creates a new object in this case?
This question is not a duplicate of this one, as I am asking specifically how the object creation happens in this case, whereas the other question was more generally about when names share objects.