Mutability Explained
Understand the #1 beginner confusion: why some structures change in place and others don’t, and how this affects copying, functions, and bugs.
Mutability means: can this object change after creation? ## Mutable structures - list - dict - set - most class objects ## Immutable structures - tuple - string - int, float, bool ## Why it matters Because it affects: - copying - passing to functions - unexpected bugs ## Example: mutable reference bug ```python a = [1, 2] b = a b.append(3) print(a) # [1, 2, 3] ``` ## Fix: copy ```python a = [1, 2] b = a.copy() b.append(3) print(a) # [1, 2] ``` ## Example: immutable is safe ```python x = "cat" y = x y = "bat" print(x) # cat ``` ## Graph: reference vs copy ```mermaid flowchart LR A[a] --> C[Same list object] B[b] --> C D[a.copy()] --> E[New list object] ``` ## Remember - Most “surprising” bugs come from mutability - Use copy() when needed - Immutable data prevents accidental changes