Python · The language, not just syntax

Why does mutability matter in Python?

MediummutabilityaliasingdefaultsUpdated Oct 2026
Quiz this track

Short answer

Mutable objects can change in place, so two names can alias the same object and observe each other's changes. Immutable objects cannot change, which makes sharing safe and enables hashing and dictionary keys.

Assignment never copies an object. It binds a name to a reference. For immutable values that distinction is invisible because nothing can change the object. For mutable values it is the source of many bugs, especially mutable default arguments and shared class attributes.

python
def add_item(item, bucket=[]):
    bucket.append(item)
    return bucket

print(add_item("a"))  # ['a']
print(add_item("b"))  # ['a', 'b']

def add_item_safe(item, bucket=None):
    if bucket is None:
        bucket = []
    bucket.append(item)
    return bucket
Default arguments are evaluated once when the function is defined. Use None and create a fresh object inside the function.

Mutable versus immutable

  • Immutable: int, float, bool, str, bytes, tuple, frozenset, Decimal
  • Mutable: list, dict, set, bytearray, most user-defined objects
  • Immutable objects can be hashable and are safe to share across threads
  • Mutable objects can be changed in place, which is efficient but requires ownership discipline

Identity and equality are separate. The is operator compares identity, and == compares value. Small integers and some strings are interned, so is may appear to work for them, but it is never the correct test for value equality. Use == for values and is only for None, True, False and sentinel objects.

The same trap applies to class attributes. A mutable class attribute such as items = [] is shared by every instance unless the instance assigns its own attribute.

Follow-ups you should expect

Interviewers use these to check whether the first answer was understanding or memorisation.

  1. 1Why is a mutable default argument dangerous?
  2. 2What is the difference between is and ==?
  3. 3Why must dictionary keys be immutable?
  4. 4How would you make a user-defined object safe to use as a key?

Say it in the interview

Mutability matters because assignment aliases objects rather than copying them. If two names point at the same list, a mutation through one is visible through the other. The classic production bug is a mutable default argument, which is evaluated once at definition time, so I use None and create the container inside. I also distinguish identity with is from value equality with ==, and only use is for None and sentinels.

Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.

Related questions

Reading is step one

Now say it out loud.

Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Python mock interview and get scored feedback on depth, clarity and confidence.