Sub topic 11
Aliasing, Shallow Copies and Deep Copies
This chapter assumes you know how to create lists, index and slice them, and call methods such as append. It covers why changing one list sometimes changes another, and how to get an independent copy.
Names refer to lists
A Python variable is a name that points to an object. Assigning a list to a second name does not copy the list. Both names point to the same object. This is called aliasing.
a = [1, 2, 3]
b = a # alias: both names refer to the same list
c = a.copy() # shallow copy: a new list
a.append(4)
print(b) # [1, 2, 3, 4]
print(c) # [1, 2, 3]
print(a is b) # True
print(a is c) # FalseThe is operator checks whether two names point to the same object. The == operator checks whether the contents are equal. Here a == c is false after the append, but a is b is always true.
Aliasing also affects functions. A function that receives a list gets a reference to the caller's list, so mutating it inside the function changes the original.
Making a shallow copy
A shallow copy creates a new outer list. It fills that list with the same item objects the original holds. Any of these makes one:
a.copy()a[:](a full slice)list(a)
For a list of numbers or strings, a shallow copy is all you need. Those items are immutable, so sharing them is harmless.
Where shallow copies fail
If the list holds mutable items, such as other lists, the copy and the original share those inner items.
original = [[1, 2], [3, 4]]
shallow = original.copy()
shallow[0].append(99)
print(original) # [[1, 2, 99], [3, 4]]
print(shallow) # [[1, 2, 99], [3, 4]]
shallow.append([5, 6])
print(original) # [[1, 2, 99], [3, 4]] (outer lists are separate)The outer lists are separate, so appending to one does not affect the other. The inner lists are shared, so changing an inner list shows up in both.
Deep copies
A deep copy duplicates the outer list and, recursively, every object inside it. Use copy.deepcopy.
import copy
original = [[1, 2], [3, 4]]
deep = copy.deepcopy(original)
deep[0].append(99)
print(original) # [[1, 2], [3, 4]]
print(deep) # [[1, 2, 99], [3, 4]]Now the two structures are fully independent.
Choosing the right tool
| Goal | Use | Inner mutable items |
|---|---|---|
| Two names, one list | `b = a` | Shared |
| New outer list | `a.copy()`, `a[:]`, `list(a)` | Shared |
| Fully independent data | `copy.deepcopy(a)` | Copied |
Common errors
- Expecting
b = ato copy. Usea.copy()when you need a separate list. - Using
[:]on a list of lists and expecting independent rows. The rows are still shared. - Mutating a list passed into a function when the caller expects it unchanged. Copy it first inside the function, or return a new list.
- Repeating a list with
*.[[0] * 3] * 2repeats references to one inner list. Build rows with a comprehension instead:[[0] * 3 for _ in range(2)].
Exercise
After running x = [[1], [2]], y = x.copy() and y[0].append(5), what does x contain? Which call would have kept x unchanged?
Show answer
x is [[1, 5], [2]], because copy() is shallow and both lists share the inner list [1]. Using y = copy.deepcopy(x) would have kept x unchanged.
Exercise
A function def add_item(items): items.append("new") is called as add_item(my_list). Does my_list change? Why?
Show answer
Yes. The parameter items is an alias for the same list object, so append mutates the caller's list. To avoid this, copy the list inside the function with items = items.copy() or return a new list.