10.11. 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:

State snapshot for multiple references (aliases) to a list

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.

Activity: CodeLens 10.11.2 (chp09_is3)

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

You have attempted of activities on this page