Interview frequency: …
Short answer
A mutable object can be changed in place (such as list, dict and set), while an immutable object cannot change after creation (such as int, str, tuple and frozenset); any "modification" of it creates a new object.
Explanation
Variables in Python are names that point to objects. After a = b both names point to the same object, so if it is mutable and you change it through one name, the change shows through the other. This matters when passing objects to functions and when using them as dict keys or set elements (they must be hashable, which usually requires immutability). Note that a tuple is immutable but may contain a mutable list, which makes it unhashable.
Code example
a = [1, 2]
b = a
b.append(3)
print(a) # [1, 2, 3] — Same object
s = "hi"
t = s
t += "!"
print(s) # hi — t Now points to a new objectCommon mistakes
- Confusing mutating an object (append) with rebinding a name (=) to a new object.
- Assuming a tuple can always be used as a dict key even when it contains a list.
Follow-up questions
- Why is a list as a default parameter value a problem?
- When should you choose a list, tuple, set or dict?