Immutable Collections
Learn when immutability is a feature: using tuples, frozenset, and safe keys in dicts, plus how immutability prevents bugs in shared state.
Immutability helps when data should never change. ## frozenset A frozenset is an immutable set. Useful when you want a set as a dict key. ```python a = frozenset([1,2,3]) b = frozenset([2,3,4]) print(a & b) ``` ## Use immutable keys safely ```python cache = {} key = ("user", 101) # tuple key cache[key] = {"name": "Tom"} print(cache[key]) ``` ## Why immutability helps - safer sharing across functions - safe keys in dict/set - fewer accidental mutations ## Graph: shared state safety ```mermaid flowchart LR A[Mutable object] --> B[Can change unexpectedly] C[Immutable object] --> D[Safe to share] ``` ## Remember - tuples and frozenset help create safe keys - immutability reduces bugs in shared code