Skip to main content

Section 9.13 Objects, References, and Aliasing

We have already seen that everything in Python is a reference. When we have code like this:
a = "banana"
b = a
The storage diagram shows us that a and b will refer to the same area in memory: a string with the letters "banana".
Since strings are immutable, Python can optimize resources by making two names that refer to the same string value refer to the same object.
Lists, however, are mutable, and this can cause some unexpected results if we try to make a copy of a list by assigning variables as follows. In this program, we use the is operator to test if two variables refer to the same object:
The reference diagram for this example looks like this:
Because both a andb refer to the same area of memory, we say the list is aliased. It also means that changing an element in b will change the corresponding element in a. Check this out in codelens:
This behavior is almost never useful; it usually causes more problems than it solves. When you use repetition with lists, these problems become even more subtle and can sneak up on you when you least expect them. In general, it is safer to avoid aliasing when you are working with mutable objects. For immutable objects, there’s no problem. That’s why Python is free to alias strings and integers when it sees an opportunity to economize. But remember: lists are mutable.

Checkpoint 9.13.1.

    What is printed by the following statements?
    a_list = [4, 2, 8, 6, 5]
    b_list = a_list
    b_list[3] = 4711
    print(a_list)
    
  • [4, 2, 8, 6, 5]
  • b_list is not a copy of a_list. It is a reference to the same list that a_list
  • [4, 2, 8, 4711, 5]
  • Yes, since a_list and b_list both reference the same list, changes to one also change the other.
How, then, can we make a copy of a list without running into problems? The answer is on the next page.