Tuples, copies and choosing the right structure
Copies, aliasing and mutable pitfalls
Goal: Predict aliasing effects and choose between shallow and deep copies · 11 min
A Python variable is a name that points to an object. Assigning one name to another does not copy the object:
a = [1, 2, 3]
b = a # same list, two names
b.append(4)
print(a) # [1, 2, 3, 4]
print(a is b) # True
is tests whether two names point to the same object; == tests whether the values are equal.
Shallow copy (a.copy(), list(a), a[:], dict.copy()) creates a new outer container but shares the inner objects:
grid = [[1, 2], [3, 4]]
shallow = grid.copy()
shallow[0].append(99)
print(grid) # [[1, 2, 99], [3, 4]] inner list shared!
Deep copy copies everything recursively:
import copy
deep = copy.deepcopy(grid)
Immutable objects (numbers, strings, tuples) cannot be changed in place, so aliasing is harmless: s = "ab"; t = s; t += "c" makes a new string for t; s stays "ab".
Classic traps:
- A mutable default argument is created once, when the function is defined, and then shared by all calls:
def add(x, items=[]): # wrong!
items.append(x); return items
Use items=None and create the list inside: if items is None: items = [].
[[0] * 3] * 2creates two references to the same row. Use[[0] * 3 for _ in range(2)].
Worked example: The shared default list
- def add(x, items=[]) uses ONE list for every call that omits items.
- add(1) → [1]; add(2) → [1, 2] — the second call sees the first call's data.
- The fix with None creates a fresh list each time.
def add(x, items=[]):
items.append(x)
return items
print(add(1))
print(add(2))
def add_ok(x, items=None):
if items is None:
items = []
items.append(x)
return items
print(add_ok(1))
print(add_ok(2))Output:
[1]
[1, 2]
[1]
[2]