Python · Fundamentals & Gotchas

Mutable vs immutable objects

Easymutableimmutabledefaultshashable

Interview question

What is the difference between mutable and immutable objects in Python?

How to answer

The short answer

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, byteslist, dict, set, bytearray, most custom objects

Why that matters:

  • Mutable default arguments are a classic bug.
  • Aliasing: two names for one mutable share edits.
Python
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 bucket

Interview tip: Lead with "can it change in place?" then give the default-argument and dict-key consequences.

Lock it in with a real drill

You remember an answer longer once you have used it. Try a hands-on problem on this concept.

Open related drill