Reassigning a reference

Now we'll modify the value of x with another assignment:

>>> x = 500

This does not result any sort of change to the int(1000) object we previously constructed. Integer objects in Python are immutable and cannot be changed. In fact, what happens here is that Python first creates a new immutable integer object with the value 500 and then redirects the x reference to point at the new object:

Figure 4.2: Reassign the name 'x' to a new integer object with the value 500

Since we have no other references to the original int(1000) object, we now have no way of reaching it from our code. As a result, the Python garbage collector ...

Get The Python Apprentice now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.