Mutable vs Immutable Types in Python — Complete Guide
The Interview Question
What is the difference between mutable and immutable types in Python? Why does it matter?
Expert Answer
In Python, every object is either mutable (can be changed after creation) or immutable (cannot be changed). Immutable types include int, float, str, tuple, frozenset, and bool. Mutable types include list, dict, set, and most custom objects. This distinction matters in three critical ways. First, when you pass a mutable object to a function, the function can modify the original — this is a common source of bugs when using default mutable arguments. Second, only immutable objects can be used as dictionary keys or set elements because their hash value must remain constant. Third, string operations like concatenation create new string objects each time, which matters for performance — joining a list of strings is O(n) while repeated concatenation is O(n²).
Key Points to Hit in Your Answer
- Immutable: int, float, str, tuple, frozenset, bool, bytes
- Mutable: list, dict, set, bytearray, custom objects
- Never use mutable default arguments (def f(lst=[]) is a classic bug)
- Immutable objects are hashable and can be dict keys
- Tuples are immutable but can contain mutable elements (tuple of lists)
- String concatenation in a loop creates n new objects — use ''.join() instead
Code Example
# The mutable default argument trap
def append_to(item, target=[]): # BAD — shared across calls
target.append(item)
return target
append_to(1) # [1]
append_to(2) # [1, 2] — NOT [2]!
# Fix: use None as default
def append_to(item, target=None):
if target is None:
target = []
target.append(item)
return target
# Immutable = hashable = can be dict keys
d = {}
d[(1, 2)] = "tuple key works" # OK — tuple is immutable
d[[1, 2]] = "list key fails" # TypeError — list is mutable
# String performance
# BAD: O(n²) — creates new string each iteration
result = ""
for s in huge_list:
result += s
# GOOD: O(n) — joins once
result = "".join(huge_list)
What Interviewers Are Really Looking For
The mutable default argument gotcha is almost guaranteed as a follow-up. If you explain it before they ask, that's a strong signal. Knowing that tuples can contain mutable elements (and therefore a tuple of lists isn't hashable) shows deeper understanding.
Practice This Question with AI Grading
Reading about interview questions is a start — but practicing with real-time AI feedback is how you actually get better. Goliath Prep grades your answers instantly and tells you exactly what you're missing.
Start Practicing Free →