Sub topic 1
Mutable and immutable objects
Every collection in this tutorial behaves the way it does because of one property: whether its contents can change after creation. This chapter builds the working model of objects, names, and mutation. The later chapters on lists, tuples, dictionaries, and sets all rely on it.
Prerequisites
This chapter assumes you can:
- Write Python variables, loops, and functions.
- Use built-in types such as
int,str, andbool. - Run Python 3 code in a REPL or a script.
You do not need to know anything about collections yet. The chapter uses lists and tuples only as examples.
Names, objects, and the three facts about an object
In Python, a variable is a name that refers to an object. The assignment x = [1, 2] does not put a list inside x. It creates a list object and binds the name x to it.
Every object has three facts:
- Identity is a unique number for the object's lifetime.
id(obj)returns it. In CPython, the standard implementation, it is the object's memory address. - Type says what the object is and what operations it supports.
type(obj)returns it. - Value is the content the object currently holds.
Two operators compare objects in different ways:
==asks whether two objects have equal values.isasks whether two names refer to the very same object, meaning the same identity.
a = [1, 2]
b = a # a second name for the same object
c = [1, 2] # a different object with an equal value
print(a == c) # True, the values are equal
print(a is c) # False, they are two separate objects
print(a is b) # True, one object with two namesThe diagram shows this layout.
What mutable and immutable mean
An object is mutable if its value can change while its identity stays the same. An object is immutable if its value can never change after creation. To get a different value from an immutable object, you must create a new object.
| Type | Mutable? | Notes |
|---|---|---|
| `int`, `float`, `bool`, `complex` | No | `x += 1` binds `x` to a new object |
| `str` | No | Methods such as `upper()` return new strings |
| `bytes` | No | The byte-string counterpart of `str` |
| `tuple` | No | Shallow: see the section on containers below |
| `frozenset` | No | The immutable form of `set` |
| `list` | Yes | Supports `append`, item assignment, `sort`, and more |
| `dict` | Yes | Supports adding, replacing, and deleting keys |
| `set` | Yes | Supports `add`, `discard`, `update`, and more |
| `bytearray` | Yes | The mutable form of `bytes` |
The four collections in this tutorial split evenly. Lists, dictionaries, and sets are mutable. Tuples are immutable.
Mutation versus rebinding
Two different things can happen to a name, and beginners often confuse them.
- Rebinding points a name at a different object. The old object is untouched.
- Mutation changes the object itself. Every name that refers to it sees the change.
Immutable objects only allow rebinding. This example uses integers and tuples:
x = 10
y = x
x += 1 # builds a new int 11 and rebinds x
print(x, y) # 11 10
old = (1, 2)
t = old
t += (3,) # builds a new tuple and rebinds t
print(old) # (1, 2)
print(t) # (1, 2, 3)
print(old is t) # FalseThe += operator looks like an in-place change, but for an immutable type it cannot be one. Python falls back to t = t + (3,).
Lists do the opposite. The += operator on a list calls an in-place method, so it mutates the existing object.
a = [1, 2]
b = a
a += [3] # mutates the shared list in place
print(b) # [1, 2, 3]
a = a + [4] # builds a new list and rebinds a
print(a) # [1, 2, 3, 4]
print(b) # [1, 2, 3], because b still refers to the old listFor lists, a += [3] and a = a + [3] look equivalent but are not. The first changes the object that b also sees. The second creates a new object. This difference causes real bugs when two names share a list.
Aliasing: shared references
When two names refer to one mutable object, the names are aliases. Changing the object through either name changes what both see. This is expected behavior, but it surprises people in three common places.
Assignment copies the reference, not the object:
original = ["a", "b"]
alias = original
alias.append("c")
print(original) # ['a', 'b', 'c']Function arguments are passed the same way. A function receives a reference to the caller's object, so it can mutate that object. The language calls this passing by object reference. Rebinding a parameter inside the function does not affect the caller, but mutating the object does:
def add_one(numbers):
numbers.append(1) # mutates the caller's list
def rebind(numbers):
numbers = numbers + [1] # creates a new list, caller unaffected
return numbers
data = [0]
add_one(data)
print(data) # [0, 1]
rebind(data)
print(data) # [0, 1], unchangedRepetition with * repeats references. The next chapter returns to this with lists of lists, but the cause belongs here: the repeated elements are one object.
row = [0, 0]
grid = [row] * 2 # two references to the same row
grid[0][0] = 5
print(grid) # [[5, 0], [5, 0]]Because immutable objects cannot change, aliasing them is harmless. If two names share the string "abc", neither can alter it. So Python is free to share immutable objects, and it sometimes does.
Copying: shallow and deep
To get an independent object instead of an alias, you must copy. There are two levels.
- A shallow copy creates a new outer container, but its elements are the same objects as in the original.
- A deep copy creates new copies of the elements too, recursively.
For a list, list.copy(), list(x), and the slice x[:] all make shallow copies. The copy module provides copy.copy (shallow) and copy.deepcopy (deep).
import copy
matrix = [[0, 0], [0, 0]]
shallow = matrix.copy()
deep = copy.deepcopy(matrix)
matrix[0][0] = 9
print(shallow) # [[9, 0], [0, 0]], the inner lists are shared
print(deep) # [[0, 0], [0, 0]], fully independentA shallow copy is enough when the elements are immutable, such as a list of numbers or strings. Use a deep copy when the elements are themselves mutable and you need independence. Deep copies cost more time and memory, so do not use them by default.
Immutability is shallow
An immutable container guarantees one thing only: the set of objects it refers to cannot change. It does not guarantee that those objects are themselves immutable. If a tuple holds a list, you cannot replace the list with another object, but you can still mutate the list.
record = ("config", [1, 2])
record[1].append(3)
print(record) # ('config', [1, 2, 3])
try:
record[1] = [9]
except TypeError as e:
print(e) # 'tuple' object does not support item assignmentThe value of record did change, because a tuple's value includes the values of the objects inside it. This has consequences for hashing. A tuple can serve as a dictionary key only if everything inside it is also hashable. The chapter on hashability explains that rule. The chapter on pitfalls revisits mutable items inside tuples.
Identity in practice
Three habits follow from this model.
Compare values with ==, not is. Python may or may not share equal immutable objects. CPython, for example, reuses small integers and some strings, but this is an implementation detail you must not rely on.
x = 1000
y = 1000
print(x == y) # True, and this is the check you should use
# x is y may be True or False depending on how the code is compiled and runUse is for singletons. None, True, and False each exist as one object, so value is None is the correct and idiomatic test.
result = None
print(result is None) # TrueDo not mutate a collection while looping over it. The loop holds a reference to the same object you are changing. Removing items while iterating a list skips elements. Iterate over a copy, or build a new collection.
numbers = [1, 2, 3, 4, 5, 6]
for n in numbers:
if n % 2 == 0:
numbers.remove(n)
print(numbers) # [1, 3, 5], the odd numbers
numbers = [1, 2, 2, 4]
for n in numbers:
if n % 2 == 0:
numbers.remove(n)
print(numbers) # [1, 2], one 2 was skippedThe first run gives the expected result only by luck. The second shows the skipped element. A list comprehension such as [n for n in numbers if n % 2 != 0] avoids the problem.
Why this matters for choosing a collection
The mutable and immutable split drives the decisions in the rest of the tutorial:
- Choose a mutable collection when contents grow, shrink, or change in place, such as a queue of tasks or a running tally.
- Choose an immutable collection when the contents represent a fixed record, when you want to protect data from accidental changes, or when you need an object that can be a dictionary key or set element.
- Any mutable collection you share between parts of a program is a source of action at a distance. Pass copies, or document who may change it.
Summary of the model
- A name refers to an object. Assignment binds names and never copies objects.
- Objects have identity, type, and value.
==compares values andiscompares identity. - Mutable objects change in place. Immutable objects are replaced by new objects.
- Aliases to a mutable object all see its changes. Copy shallowly or deeply when you need independence.
- Immutability is shallow. A tuple can hold a mutable object, and that object can still change.
Exercise
After running the code below, what do a, b, and c contain, and which names refer to the same object?
a = [1, 2]
b = a
c = a.copy()
b += [3]
c = c + [4]
Show answer
a and b both contain [1, 2, 3], and they are the same object. b += [3] mutates the shared list in place, so a sees it. c starts as a separate shallow copy [1, 2], and c = c + [4] creates yet another new list, so c contains [1, 2, 4] and does not affect a or b.
Exercise
A function def tag(items): items.append("x"); return items is called as result = tag(names) with names = ["a"]. What does names contain afterward, and how would you change the function so the caller's list is left alone?
Show answer
names contains ["a", "x"], because the function mutates the list it received, and result is the same object as names. To leave the caller's list alone, build a new list inside the function, for example return items + ["x"], or copy first with items = list(items) and then append.
Exercise
Given t = (1, [2, 3]), explain why t[1].append(4) works but t[1] = [2, 3, 4] raises a TypeError.
Show answer
A tuple cannot rebind its slots, so assigning to t[1] fails. The list stored in that slot is a mutable object, and append changes the list itself without changing which object the tuple refers to. Tuple immutability is shallow.