Mutability and equality¶
This notebook covers roughly the same ground as this video
Python lists are mutable. We can define a list, change the second element and add another element to the end as follows.
l = [11, 22, 33, 44]
print(l)
l[1] = 22222 # Change the second element (note: first element is l[0], second is l[1])
print(l)
l.append(555) # Add 555 on the end
print(l)
Sets are also mutable.
s = {1, 10, 100, 1000}
print(s)
s.add(10000) # Add 10000 to the set
s.remove(1) # Remove 1 from the set
print(s)
Tuples are not mutable. You can replace a tuple by a completely new one, but you cannot modify one that already exists.
t = (11, 22, 33, 44)
print(t)
t = (11, 22, 33, 44, 55) # This is a new tuple, not a change to the old one
print(t)
t[1] = 22222 # This will fail
t.append(555) # This will fail
Strings are also not mutable.
u = "The cat sat on the mat"
print(u)
print(u.upper()) # This is a new string, not a change to the old one
print(u)
u[4] = 'b' # This will fail
Given two lists l and m, we can check whether they are the same by entering l == m or l is m. These are subtly different. In the code below, we define l and m to both be [1,2,3,4]. However, these are two separate copies of the same list, saved in different places. We can alter l without altering m and vice versa. We then have the line n = l. This makes n into a new name for the list l, but it does not create a new list. Because l and n are two names for the same thing, if we alter l then n will also change, and vice versa.
To check whether two lists have the same elements, we use ==. By this test, l, m and n are all the same. To check whether two variables are different names for the same thing, we instead use the keyword is. By this test, l and n are the same but m is different.
l = [1, 2, 3, 4]
m = [1, 2, 3, 4]
n = l
print(l == m)
print(l == n)
print(l is m)
print(l is n)
l.append(999) # This will change both l and n but not m
print(l)
print(m)
print(n)
True True False True [1, 2, 3, 4, 999] [1, 2, 3, 4] [1, 2, 3, 4, 999]
Every Python object has an id number. As another way to check whether two variables are just alternative names for the same thing, we can compare the id numbers:
print(f'{id(l)=}')
print(f'{id(m)=}')
print(f'{id(n)=}')
id(l)=2355545641728 id(m)=2355545646464 id(n)=2355545641728