References to mutable objects

Python objects show this name-binding behavior for all types. The assignment operator only ever binds object to names, it never copies an object by value. To help make this point crystal clear, let's look at another example using mutable objects: Lists. Unlike the immutable ints that we just looked at, list objects have mutable state, meaning that the value of a list object can change over time.

To illustrate this, we first create an list object with three elements, binding the list object to a reference named r:

>>> r = [2, 4, 6]
>>> r
[2, 4, 6]

We then assign the reference r to a new reference s:

>>> s = r
>>> s
[2, 4, 6]

The reference-object diagram for this situation makes it clear that we have two names referring to a single list instance:

Figure 4.9: 's' and 'r' refer to the same list object

When we modify the list referred to by s by changing the middle element, we see that the list referred to by r has changed as well:

>>> s[1] = 17
>>> s
[2, 17, 6]
>>> r
[2, 17, 6]

Again, this is because the names s and r refer to the same mutable object , a fact that we can verify by using the is keyword which we learned about earlier:

>>> s is r
True

The main point of this discussion is that Python doesn't really have variables in the metaphorical sense of a box holding a value. It only has named references to objects, and these references behave more like labels which allow us to retrieve objects. That said, it's still common to talk about variables in Python because it's convenient. We will continue to do so throughout this book, secure in the knowledge that you now understand what's really going on behind the scenes.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset