Sub topic 2
Mutability and aliasing
This chapter assumes you know that a Python variable is a name bound to an object, and that is compares identity while == compares value. You should also be comfortable with lists, dictionaries, and function calls.
Mutable and immutable objects
An object is mutable if its contents can change in place without changing its identity. Lists, dictionaries, sets, and most user-defined class instances are mutable. Integers, strings, tuples, and frozensets are immutable. An operation on an immutable object returns a new object.
Two names bound to one object are aliases. With an immutable object, aliasing is harmless because nobody can change the shared object. With a mutable object, a change made through one name is visible through every other name.
a = [1]
b = a
b.append(2)
print(a) # [1, 2]
print(a is b) # True
c = list(a)
print(a is c) # FalseAssignment never copies. b = a binds a second name to the same list. Calling list(a) builds a new list, so c is a distinct object.
Rebinding versus mutating
Two different operations are easy to confuse:
- Rebinding points a name at a different object, as in
x = [9]. Other names are unaffected. - Mutating changes the object itself, as in
x.append(9). Every alias sees the change.
The augmented assignment += depends on the type. For a list it calls __iadd__, which mutates in place. For a tuple or an integer it builds a new object and rebinds the name.
x = [1]
y = x
x += [2] # mutates the shared list
print(y) # [1, 2]
s = (1,)
t = s
s += (2,) # builds a new tuple and rebinds s
print(t) # (1,)Aliasing through function calls
Python passes arguments by binding the parameter name to the caller's object. This is sometimes called "pass by object reference." A function that mutates a mutable argument changes the caller's object.
def add_item(items, value):
items.append(value)
data = []
add_item(data, 5)
print(data) # [5]A related error is a mutable default argument. The default value is created once, when the def statement runs, and every call that omits the argument shares it.
def collect(value, bucket=[]):
bucket.append(value)
return bucket
print(collect(1)) # [1]
print(collect(2)) # [1, 2] the same list as beforeThe usual fix is to use None as the default and create the list inside the function.
def collect(value, bucket=None):
if bucket is None:
bucket = []
bucket.append(value)
return bucketShallow copies share nested objects
list(a), a.copy(), and a[:] make shallow copies. The new container is distinct, but it refers to the same elements. If those elements are mutable, they are still shared. Use copy.deepcopy to copy the nested objects as well.
import copy
original = [[1], [2]]
shallow = list(original)
deep = copy.deepcopy(original)
original[0].append(99)
print(shallow[0]) # [1, 99] the inner list is shared
print(deep[0]) # [1] the inner list was copiedA common version of this error is grid = [[0] * 3] * 3. It makes three references to one inner list. Write [[0] * 3 for _ in range(3)] to get three separate rows.
Why this matters for memory
An aliased object stays alive as long as any name or container refers to it. A "copy" that is really an alias saves memory but shares state. A deep copy gives you independence but doubles the memory. The next chapter shows how CPython tracks these references.
Exercise
After a = [[1, 2], [3]], b = a[:], and b[0].append(9), what does a contain, and why? What does a contain if you run b.append([4]) instead?
Show answer
With b[0].append(9), a is [[1, 2, 9], [3]]. The slice makes a shallow copy, so b[0] and a[0] are the same inner list. With b.append([4]), a is unchanged at [[1, 2], [3]], because b is a separate outer list and the append changes only that list.