Skip to content
LakeBench
ProblemsCommunityPricing
Sign inStart practicing
Back
  1. Home
  2. Interview prep
  3. Mutable vs immutable objects

Python · Fundamentals & Gotchas

Mutable vs immutable objects

Easypython-36
mutableimmutabledefaultshashable

Question

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

Solution

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 bucket

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

🎯 Put this concept into practice

Solidify this answer with real hands-on interview drills in the browser studio.

Open related drill →
PreviousNext