Guide Python Intermediate

5.9 Mutable vs Immutable Types

The difference between mutable and immutable objects in Python, which built-in types fall into each category, and how identity (id()) behaves differently for each.

2 min read

Definition

What Is It?

A MUTABLE object’s value can be changed in place after creation (its id stays the same); an IMMUTABLE object’s value can never change — any “modification” actually creates a brand-new object.

Why Does It Matter?

This affects correctness (shared references to mutable objects can surprise you), safety (immutable objects are safe to share across threads), and what can be used as a dict key.

flowchart TD subgraph Immutable["Immutable — t = (1, 2); t = t + (3,)"] T1["t → (1, 2)\nid: 0x1001"] -->|"t = t + (3,)"| T2["t → (1, 2, 3)\nid: 0x2002 — a NEW object"] end subgraph Mutable["Mutable — l = [1, 2]; l.append(3)"] L1["l → [1, 2]\nid: 0x3003"] -->|"l.append(3)"| L2["l → [1, 2, 3]\nid: 0x3003 — the SAME object"] end

Mutating a mutable object keeps its identity; “mutating” an immutable one creates a new object.

Examples

MutableImmutable
listtuple
dictstr
setint, float, bool, complex
bytearraybytes, frozenset

Memory Behavior

How Is It Used?

Mutating a list in place leaves its identity (id) unchanged; reassigning a tuple’s contents is impossible, so any “change” produces a new object with a new id:

>>> l = [1, 2, 3]
>>> id(l)
140420020687424
>>> l.append(4)     # in-place mutation
>>> id(l)           # SAME id -- same object, modified
140420020687424

Comparison Table

PropertyMutableImmutable
Can change after creation?YesNo
Safe to use as dict key?No (unhashable)Yes (if hashable)
Safe to share across threads?Requires careInherently safe
id() after modificationUnchangedN/A — new object created

Quick Interview Answer

“A mutable object’s value can change in place — its id stays the same after modification, like a list.append(). An immutable object’s value can never change — any apparent ‘modification’ actually builds a brand-new object with a new id, like tuple + (3,). This is why only immutable, hashable types can be used as dict keys or set members, and why immutable objects are inherently safer to share across threads.”

Common Mistakes

  • Assuming tuple + (x,) modifies the tuple in place — it creates and returns an entirely new tuple; the original is untouched.
  • Sharing a mutable default or a mutable object across function calls without realizing all references point to the same underlying object.
  • Trying to use a list or dict as a dict key, hitting TypeError: unhashable type, instead of reaching for the immutable equivalent (tuple, frozen structure).

Add More Questions to This Guide

Know a question that should be here? Share it and help the community!

Open Google Form