Immutable objects cannot change their value in place after creation. Any "change" creates a new object (or rebinds a name).
Mutable objects can change contents in place; names pointing at them see the update.
| Immutable (common) | Mutable (common) | | --- | --- | | int, float, bool, str, tuple, frozenset, bytes | list, dict, set, bytearray, most custom objects |
Why that matters:
- Mutable default arguments are a classic bug.
- Aliasing: two names for one mutable share edits.
s = "hi"
print(id(s))
s = s + "!" # new str object; name rebound
print(id(s))
lst = [1, 2]
alias = lst
alias.append(3)
print(lst) # [1, 2, 3] shared object
# Dangerous default
def add_item(item, bucket=[]):
bucket.append(item)
return bucket
print(add_item("a"))
print(add_item("b")) # ['a', 'b'] same default list
def add_item_safe(item, bucket=None):
if bucket is None:
bucket = []
bucket.append(item)
return bucketInterview tip: Lead with "can it change in place?" then give the default-argument and dict-key consequences.