Skip to main content

Foundations of Python Programming: Functions First

Section 9.5 Aliasing

Since variables refer to objects, if we assign one variable to another, both variables refer to the same object:
In this case, the reference diagram looks like this:
Because the same list has two different names, a and b, we say that it is aliased. Changes made with one alias affect the other. In the codelens example below, you can see that a and b refer to the same list after executing the assignment statement b = a.
Although this behavior can be useful, it is sometimes unexpected or undesirable. In general, it is safer to avoid aliasing when you are working with mutable objects. Of course, 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.
Check your understanding

Checkpoint 9.5.1.

    What is the value of y after the following code has been evaluated:
    w = ['Jamboree', 'get-together', 'party']
    y = ['celebration']
    y = w
    
  • [’Jamboree’, ’get-together’, ’party’]
  • Yes, the value of y has been reassigned to the value of w.
  • [’celebration’]
  • No, that was the inital value of y, but y has changed.
  • [’celebration’, ’Jamboree’, ’get-together’, ’party’]
  • No, when we assign a list to another list it does not concatenate the lists together.
  • [’Jamboree’, ’get-together’, ’party’, ’celebration’]
  • No, when we assign a list to another list it does not concatenate the lists together.

Checkpoint 9.5.2.

    What is printed by the following statements?
    alist = [4,2,8,6,5]
    blist = alist
    blist[3] = 999
    print(alist)
    
  • [4,2,8,6,5]
  • blist is not a copy of alist, it is a reference to the list alist refers to.
  • [4,2,8,999,5]
  • Yes, since alist and blist both reference the same list, changes to one also change the other.
You have attempted of activities on this page.