Mutable and immutable objects#
import numpy as np
There is a distinction in Python between container objects that are mutable and those that are immutable.
Container objects are objects that contain a collection of other objects.
One example of container object is a list:
# A list. Notice the square brackets.
a = [1, 2, 3]
A list is mutable. This means that we can change the values inside the list without having to make a new value. For example:
a[1] = 99
a
[1, 99, 3]
Notice that a
is the same value that we created in the first cell, but the
contents of that value have changed — the second element is now 99. The list
is mutable.
The tuple is another type of container object. In many ways it is similar to a list, but, by contrast, tuples are immutable by design:
# A tuple. Notice the round brackets (parentheses).
t = (1, 2, 3)
t
(1, 2, 3)
Trying to set any value contained in the tuple raises an error:
t[1] = 99
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[5], line 1
----> 1 t[1] = 99
TypeError: 'tuple' object does not support item assignment
Examples of mutable and immutable containers#
Immutable:
Tuple (
tuple
)String (
str
)
Mutable:
List (
list
)Dictionary (
dict
)Array (
np.array
)
Strings are containers for characters — a string represents a sequence of characters. They are immutable.
# Setting character in string raises error
s = 'My string'
s[1] = 'i'
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[6], line 3
1 # Setting character in string raises error
2 s = 'My string'
----> 3 s[1] = 'i'
TypeError: 'str' object does not support item assignment
However, dictionaries are mutable:
wages = dict(Liverpool=160_868_000,
Everton=80_707_000,
Leeds=20_800_000)
wages
{'Liverpool': 160868000, 'Everton': 80707000, 'Leeds': 20800000}
We can change the keys and values contained in the dictionary:
wages['Liverpool'] = 164_000_000
# The original wages value has changed.
wages
{'Liverpool': 164000000, 'Everton': 80707000, 'Leeds': 20800000}
Arrays are mutable:
arr = np.array([1, 2, 3])
arr[0] = 99
arr
array([99, 2, 3])
And this matters because?#
Actually, we can often forget about whether an object is mutable or not, but it does sometimes matter.