Sub topic 1
Mutable and Immutable Objects
Prerequisites
Assume you know Python variables, loops, functions, and basic types such as int, str, and bool. You should also be able to run Python 3 code in a script or REPL.
Mutable and immutable objects
A mutable object can change after creation. An immutable object cannot change; an operation that appears to modify it creates a new object instead.
This difference affects aliases. An alias is another variable referring to the same object.
numbers = [1, 2]
alias = numbers
alias.append(3)
print(numbers) # [1, 2, 3]
print(numbers is alias) # True
name = "Ada"
other_name = name
name = name + " Lovelace"
print(other_name) # Ada
print(name) # Ada LovelaceThe list changed in place, so both variables observe the change. The string did not change. Python created a new string and made name refer to it.
Lists: ordered collections you can change
A list is an ordered, mutable sequence. It keeps elements in position order and supports indexing, slicing, and in-place updates.
scores = [90, 85]
scores.append(77)
scores[0] = 95
print(scores) # [95, 85, 77]Use a list when the collection may grow, shrink, or have its elements replaced. Lists can contain duplicate values and values of different types, although keeping related types together usually makes code clearer.
Tuples: fixed records and unpacking
A tuple is an ordered, immutable sequence. It is useful for a fixed group of values, such as a coordinate or a function result.
point = (3, 4)
x, y = point
print(x, y) # 3 4
try:
point[0] = 1
except TypeError as error:
print(error)Tuple unpacking assigns each element to a variable. A tuple itself cannot be changed, but immutability is shallow: a tuple can contain a mutable object.
record = ("Ada", [90, 95])
record[1].append(100)
print(record) # ('Ada', [90, 95, 100])Exercise
What happens to items after alias = items followed by alias.append("new")?
Show answer
items also contains "new" because both variables refer to the same mutable list.