Aliasing and mutability
Draw names as arrows to list objects, say when two names share one list, copy a list with a slice or list(), and say what a function that changes its list argument does to the caller.
It opens on
a = [1, 2, 3], then b = a, then b.append(4), then print(a). Does it print [1, 2, 3] or [1, 2, 3, 4]?
Why it matters
Many real list bugs are one list changed through a second name, a function that quietly changes the caller's data, or a default list shared by every call; the picture of names pointing at objects explains all of them.
Good to know first
- Lists: indexing and mutation: append changes a list in place and returns None
- Defining and calling functions: a parameter takes the value of the argument
- Default and keyword arguments and docstrings: a default is used when the argument is left out
Step by step
Two names, one list
Draw b = a as two names pointing at one list, and tell a change to the list from a change of what a name points to.
The line b = a does not copy the list. It points b at the same object that a points to, so now there are two names for one list, called aliases.
two names, one list
A common mix-up
b = a makes b a copy of a.
In fact: It makes a second name for the same list, so a change through b shows through a.
Copies, and is against ==
Make an independent copy with a slice or list(), and tell is from == on lists.
After lines 2 and 3 there are three list objects, each with the items 1, 2 and 3, and each name points to its own.
three lists
A common mix-up
a == c being True means a and c are one list.
In fact: Equal items can sit in two separate lists, and is tells them apart.
Functions and the shared default
Tell a function that changes its list argument from one that only re-points its parameter, and explain what a default list does across calls.
add_one(nums) runs lst.append(1), which changes the shared list, so print(nums) on line 9 showed [7, 8, 1] although the function returned nothing.
A common mix-up
a function gets its own copy of a list argument.
In fact: The parameter is a name for the caller's list, so changes to the object are seen by the caller.
Try it
With p = [1], q = p, q.append(2) and q.append(3), what do print(p) and print(len(q)) show?Answer
[1, 2, 3] and 3
Hint: One list, two names
For w = [8, 9] and z = w[:], what does w == z give, and what does w is z give?Answer
True and False
Hint: Equal items, two objects
For def f(l): l.append(l[0]) and g = [3], what does print(g) show after f(g)?Answer
[3, 3]
Hint: l is another name for g's list
Line 3 is b.append(4), which changes the list that b points to. What does print(a) show?Answer
[1, 2, 3, 4], because there is only one list and a points to it too.
What do a == c and a is c give on line 4?Answer
True and False, since the items are equal but the lists are two objects.
