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 what happens when two names refer to one list, how to make a real copy, and why a copy of a nested list can still share data with the original.
Names refer to objects
A Python variable is a name that points to an object. It does not hold the object's contents. Assigning one name to another copies the pointer and leaves the list alone.
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) # FalseTwo names for one object are called aliases. Because lists are mutable, a change made through one alias is visible through the other. The is operator tests whether two names refer to the same object. The == operator tests whether the contents are equal. a == c is False here only because a has grown. Before the append, it was True, while a is c was already False.
Where aliasing bites
Aliasing is often useful, because it lets a function modify the list it receives. It becomes a bug when you did not intend the sharing.
def add_total(values):
values.append(sum(values))
return values
scores = [10, 20]
report = add_total(scores)
print(scores) # [10, 20, 30]
print(report) # [10, 20, 30]The function received a reference to scores, so append changed the caller's list. If the caller wants to keep the original, the function should work on a copy, or the caller should pass one.
def add_total_safe(values):
result = values.copy()
result.append(sum(result))
return result
scores = [10, 20]
print(add_total_safe(scores)) # [10, 20, 30]
print(scores) # [10, 20]A similar trap occurs with default arguments. A default value is created once, when the function is defined, so a mutable default is shared across calls.
def collect(item, bucket=[]):
bucket.append(item)
return bucket
print(collect(1)) # [1]
print(collect(2)) # [1, 2]The usual fix is to use None as the default and create the list inside the function.
def collect(item, bucket=None):
if bucket is None:
bucket = []
bucket.append(item)
return bucket
print(collect(1)) # [1]
print(collect(2)) # [2]Making a shallow copy
A shallow copy is a new list object that holds the same items as the original. Python offers several ways to make one, and they all behave the same.
original = [1, 2, 3]
copy1 = original.copy()
copy2 = list(original)
copy3 = original[:]
print(copy1 == original, copy1 is original) # True False
print(copy2 == original, copy2 is original) # True False
print(copy3 == original, copy3 is original) # True FalseUse whichever your codebase prefers. copy() states the intent most clearly. list(x) has the advantage of accepting any iterable, not only lists. x[:] is older and works on any sequence that supports slicing, but it is less obvious to a new reader.
Note that x[:] on the left side of an assignment does something different. It replaces the contents of the existing list in place, so every alias sees the change.
a = [1, 2, 3]
b = a
a[:] = [9, 9]
print(b) # [9, 9]
a = [7, 7] # rebinding: a now points to a new list
print(b) # [9, 9]Rebinding a name with = never changes the object that other names still point to. Mutation through a method, an index or a slice does.
Why shallow is not always enough
A shallow copy duplicates only the outer list. The items inside are the same objects as before. For integers and strings this does not matter, because they cannot be changed. For items that are themselves mutable, such as inner lists, the copy and the original share them.
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]]
print(shallow) # [[1, 2, 99], [3, 4], [5, 6]]Appending to the outer shallow list affected only the copy. Appending to an inner list affected both, because both outer lists hold a reference to that one inner list.
Deep copies
A deep copy duplicates the outer list and, recursively, every mutable object inside it. The standard library provides copy.deepcopy for this.
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]]deepcopy also handles lists that contain themselves and objects that appear several times. It keeps a memo of what it has already copied, so shared structure in the original stays shared in the copy, and cycles do not cause infinite recursion.
import copy
shared = [0]
data = [shared, shared]
clone = copy.deepcopy(data)
clone[0].append(1)
print(clone) # [[0, 1], [0, 1]]
print(clone[0] is clone[1]) # True
print(shared) # [0]Deep copying has costs. It takes time and memory proportional to the whole structure. It can also fail or behave oddly on objects that cannot be copied, such as open files or locks. Choose it when you really need full independence. If the inner items are immutable, or you only need to change the outer list, a shallow copy is enough.
Copying and slicing nested data without sharing
Sometimes you only need independent rows, and a full deepcopy would be heavy. A comprehension that copies each inner list gives you that for one level of nesting.
original = [[1, 2], [3, 4]]
rows_copied = [row.copy() for row in original]
rows_copied[0].append(99)
print(original) # [[1, 2], [3, 4]]
print(rows_copied) # [[1, 2, 99], [3, 4]]This stops working once the nesting goes deeper than two levels. Inner rows that contain further lists would still be shared.
The same sharing problem appears when you build a list by repetition. Multiplying a list repeats references, not objects.
bad = [[0] * 3] * 2
bad[0][0] = 1
print(bad) # [[1, 0, 0], [1, 0, 0]]
grid = [[0] * 3 for _ in range(2)]
grid[0][0] = 1
print(grid) # [[1, 0, 0], [0, 0, 0]]In bad, both rows are the same inner list. Repetition is safe when the repeated item is immutable, as in [0] * 3. The comprehension in grid evaluates [0] * 3 once per row, which creates a separate list each time.
Choosing the right kind of copy
| Situation | Use |
|---|---|
| You want a second name for the same list | Plain assignment, `b = a` |
| The list holds only immutable items (numbers, strings, tuples of those) | `a.copy()`, `list(a)` or `a[:]` |
| You will change the outer list only (add, remove, sort) | Shallow copy |
| You will change inner lists and must not affect the original | `copy.deepcopy(a)` or a per-row copy |
| A function should not modify its argument | Copy inside the function, or document that it mutates |
Common errors
- Expecting
b = ato copy. It never does. Check witha is b. - Expecting
.copy()to protect inner lists. It copies one level only. - Writing
x = x.sort()ory = x.append(1). These methods returnNone, so the name now refers toNone. This is a different bug from aliasing, but it often appears in the same code, when people try to get a "new" list from a mutating method. - Using
sorted(x)and assuming it deep copies.sortedreturns a new outer list with the same inner objects. - Passing a mutable default argument and seeing state leak between calls.
Exercise
What does this code print, and why? Then change one line so the final print shows [[1, 2], [3, 4]]. import copy a = [[1, 2], [3, 4]] b = a.copy() b[1].append(5) print(a)
Show answer
It prints [[1, 2], [3, 4, 5]]. The call a.copy() makes a new outer list, but b[1] and a[1] are the same inner list object, so appending to b[1] changes what a shows. To keep a unchanged, replace the copy line with b = copy.deepcopy(a). A per-row copy, b = [row.copy() for row in a], also works.
Exercise
A function def normalize(values): values.sort(); return values is called as ordered = normalize(data). Why might the caller be surprised, and how can the function be rewritten to avoid it?
Show answer
Because sort() reorders the list in place, the caller's data is reordered too, and ordered is the same object as data. Rewrite it to return a new list: def normalize(values): return sorted(values). The sorted function leaves its argument unchanged.