Data Structures18 min read

Immutable Collections

Learn when immutability is a feature: using tuples, frozenset, and safe keys in dicts, plus how immutability prevents bugs in shared state.

David Miller
November 16, 2025
3.7k104

Immutability helps when data should never change.

frozenset

A frozenset is an immutable set.
Useful when you want a set as a dict key.

a = frozenset([1,2,3])
b = frozenset([2,3,4])

print(a & b)

Use immutable keys safely

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

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
#Python#Advanced#Immutability