Everything in Python is an object, and a variable is just a name that points to an object. Understanding which objects can be modified (mutable) and which cannot (immutable) explains many behaviors that surprise beginners.
Mutable and immutable
| Immutable | Mutable |
|---|---|
int, float, bool | list |
str | dict |
tuple | set |
frozenset, bytes | Almost any object of a custom class |
An immutable object never changes: operations such as n += 1 or s + "!" create a new object. A mutable one can be modified in place (append, update, assignment to an index).
def add_item(x, items):
items.append(x) # modifies the original list
def add_one(n):
n += 1 # creates a new integer; the original does not change
return n
data = [1]
add_item(2, data)
print(data) # [1, 2]
n = 5
add_one(n)
print(n) # 5
t = (1, 2)
# t[0] = 9 # TypeError: tuples cannot be modified
Identity versus equality
== asks whether two objects have the same value; is asks whether they are the same object. To compare with None, True or False use is; for everything else, ==.
a = [1, 2, 3]
b = a
c = [1, 2, 3]
print(a == c) # True same value
print(a is c) # False different objects
print(a is b) # True the same object
print(id(a) == id(b)) # True id() identifies the object
x = None
print(x is None) # True for None ALWAYS use is
Shallow and deep copies
When a mutable object contains other mutable objects, a shallow copy (copy.copy, list.copy(), list(l)) duplicates the container but shares the inner objects. copy.deepcopy duplicates the whole tree of objects.
import copy
a = [[1, 2], [3, 4]]
b = copy.copy(a) # shallow: the inner lists are shared
c = copy.deepcopy(a) # deep: everything is duplicated
a[0].append(99)
print(b) # [[1, 2, 99], [3, 4]]
print(c) # [[1, 2], [3, 4]]
- Beware of mutable default values in functions (
def f(x=[])): they are created once and shared between calls. UseNoneand create the list inside. - A function that receives a mutable object can modify it: document whether it does, or work on a copy.
- Dictionary keys and set elements must be immutable (hashable).
You practice it in Spot the alias and Shallow versus deep copy.