Can someone explain why the example with integers results in different values for x and y and the example with the list results in x and y being the same object?
<
If you do y = x
, y and x are the reference to the same object. But integers are immutable and when you do x + 1
, the new integer is created:
>>> x = 1
>>> id(x)
135720760
>>> x += 1
>>> id(x)
135720748
>>> x -= 1
>>> id(x)
135720760
When you have a mutable object (e.g. list, classes defined by yourself), x is changed whenever y is changed, because they point to a single object.