Sub topic 4
Lists are mutable
This chapter covers what it means for a list to be mutable, how that differs from immutable types, and what follows from it: identity, in-place changes, and shared references. It assumes you can run a script or REPL, know int, str and bool, write for loops and if statements, and call functions and methods.
What mutable means
An object is mutable if you can change its contents after you create it, without making a new object. A list is mutable. A string, a tuple and an integer are not.
Compare a string with a list:
word = "cat"
try:
word[0] = "b"
except TypeError as error:
print(error) # 'str' object does not support item assignment
letters = ["c", "a", "t"]
letters[0] = "b"
print(letters) # ['b', 'a', 't']The string rejects the assignment. The list accepts it and now holds a different first item. The list object is the same one as before. Only its contents changed.
Identity and equality
Every Python object has an identity, a number that stays fixed for the object's lifetime. The built-in id() function returns it. The is operator compares identities. The == operator compares values.
items = [10, 20, 30]
before = id(items)
items[0] = 99
items.append(40)
print(items) # [99, 20, 30, 40]
print(id(items) == before) # True: same object, changed contents
other = [99, 20, 30, 40]
print(items == other) # True: equal values
print(items is other) # False: two separate objectsMutating a list never changes its identity. This is the core of mutability. When the contents change, every name that refers to that list sees the change.
Rebinding versus mutating
Two different operations are easy to confuse.
- Mutating changes the object that a name refers to.
- Rebinding makes a name refer to a different object. The old object is unchanged.
a = [1, 2, 3]
b = a
a.append(4) # mutation: the shared object changes
print(b) # [1, 2, 3, 4]
a = [9, 9] # rebinding: a now points to a new list
print(b) # [1, 2, 3, 4] (b still points to the old list)After b = a, both names refer to one list. Appending through a changes that one list, so b shows it. The later line a = [9, 9] does not touch the list at all. It only moves the name a.
Ways to change a list in place
Lists support several kinds of in-place change. Later chapters cover each in detail. This table is a map of them.
| Operation | Example | Effect |
|---|---|---|
| Item assignment | `xs[1] = "x"` | Replaces one item |
| Slice assignment | `xs[1:3] = [7, 8, 9]` | Replaces a range, and the length can change |
| Add methods | `xs.append(4)` | Adds items |
| Remove methods | `xs.pop()` | Removes items |
| `del` statement | `del xs[0]` | Removes an item or a slice |
| Reordering | `xs.sort()` | Changes the order |
| Augmented assignment | `xs += [5]` | Extends the same list |
Slice assignment deserves a closer look, because it can change the length of the list.
xs = [0, 1, 2, 3, 4]
xs[1:3] = ["a", "b", "c", "d"] # replace 2 items with 4
print(xs) # [0, 'a', 'b', 'c', 'd', 3, 4]
xs[1:5] = [] # replace 4 items with nothing
print(xs) # [0, 3, 4]
xs[1:1] = ["new"] # empty slice: insert without removing
print(xs) # [0, 'new', 3, 4]The right side of a slice assignment must be an iterable. Assigning a bare integer raises a TypeError.
Methods return None
Methods that mutate a list in place return None, with the exception of pop, which returns the removed item. This is a deliberate convention in Python. A function that changes an object returns nothing, so that you cannot mistake it for one that builds a new object.
nums = [3, 1, 2]
result = nums.sort()
print(result) # None
print(nums) # [1, 2, 3]This leads to a classic bug:
nums = [3, 1, 2]
nums = nums.sort() # wrong: nums is now None
print(nums) # NoneIf you want a new sorted list and want to keep the original, use sorted(nums), which returns a new list. If you want to change the list you have, call nums.sort() and do not assign the result.
Augmented assignment and `+`
The + operator and the += operator look alike but behave differently on lists.
a = [1, 2]
b = a
a = a + [3] # builds a new list, then rebinds a
print(a) # [1, 2, 3]
print(b) # [1, 2]
a = [1, 2]
b = a
a += [3] # extends the existing list in place
print(a) # [1, 2, 3]
print(b) # [1, 2, 3]a + [3] creates a new list and the name a is rebound to it. a += [3] calls the in-place extend operation, so the object that b also refers to changes. For immutable types such as tuples, += has to build a new object. For lists it mutates. This difference matters whenever more than one name refers to the same list.
Mutation through function arguments
Python passes a reference to the object into a function. If the function mutates a list parameter, the caller's list changes.
def add_total(values):
values.append(sum(values))
scores = [4, 5, 6]
add_total(scores)
print(scores) # [4, 5, 6, 15]A function that rebinds its parameter does not affect the caller:
def reset(values):
values = [] # rebinds the local name only
scores = [4, 5, 6]
reset(scores)
print(scores) # [4, 5, 6]To empty the caller's list, mutate it: values.clear() or values[:] = [].
Mutable default arguments cause a related bug. The default value is created once, when the function is defined, and then shared across calls.
def collect(item, bucket=[]):
bucket.append(item)
return bucket
print(collect(1)) # [1]
print(collect(2)) # [1, 2] (the same default list is reused)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]Mutable does not mean hashable
Because a list can change, Python does not let you use it as a dictionary key or a set member. Those structures rely on a hash value that must stay constant while the object is stored.
try:
{[1, 2]: "pair"}
except TypeError as error:
print(error) # unhashable type: 'list'
key = tuple([1, 2])
print({key: "pair"}) # {(1, 2): 'pair'}When you need a sequence as a key, convert it to a tuple.
Mutating a list while you loop over it
The loop keeps an internal position, and removing items shifts the items after the removal point. The loop then skips some of them.
nums = [1, 2, 2, 3, 4]
for n in nums:
if n % 2 == 0:
nums.remove(n)
print(nums) # [1, 2, 3] (a 2 survived; the loop skipped it)Safer alternatives are to build a new list or to loop over a copy.
nums = [1, 2, 2, 3, 4]
odds = [n for n in nums if n % 2 != 0]
print(odds) # [1, 3]
for n in nums.copy():
if n % 2 == 0:
nums.remove(n)
print(nums) # [1, 3]Chapters on iteration and pitfalls return to this.
Choosing between mutating and building new
Both styles are valid. The choice depends on who else holds a reference to the list.
- Mutate when the list is a local working buffer, when memory matters, or when the caller expects the change.
- Build a new list when other code holds a reference you should not disturb, when you are writing a function that should have no side effects, or when the result is easier to reason about as a fresh value.
- Document it either way. A function that mutates its argument should say so, and should return
Noneto match the standard library convention.
Exercises
Exercise
What does this code print, and why? x = [1, 2] y = x x += [3] x = x + [4] print(x, y)
Show answer
It prints [1, 2, 3, 4] [1, 2, 3]. The line x += [3] extends the shared list in place, so both x and y see [1, 2, 3]. The line x = x + [4] builds a new list and rebinds x to it, so y still refers to the earlier list [1, 2, 3].
Exercise
A function is meant to remove all negative numbers from the list it receives, so the caller's list is changed. The body is values = [v for v in values if v >= 0]. Why does the caller's list stay the same, and how do you fix it?
Show answer
The assignment rebinds the local name values to a new list and leaves the caller's list untouched. To mutate the original, use slice assignment: values[:] = [v for v in values if v >= 0].