Guide Python Intermediate

12.11 Frozen Sets

frozenset -- the immutable counterpart to set -- same union/intersection/membership behavior, but no add(), remove(), or update(), which is exactly what makes it hashable and usable as a dict key or set member.

2 min read
flowchart LR subgraph S["set {1, 2, 3}"] S1["Mutable"] S2["Not hashable"] end subgraph F["frozenset({1, 2, 3})"] F1["Immutable"] F2["Hashable"] end

Same operations as a regular set — union, intersection, membership — minus mutability.

What Is frozenset?

The immutable counterpart to set — same union/intersection/membership behavior, but no add(), remove(), or any method that would modify it. Because it’s immutable, it’s hashable, and therefore usable as a dict key or as a member of another set (which a regular set can never be) — the exact same trade-off covered for tuples in 11.9 Immutability and Copying.

Creating frozensets

>>> fs = frozenset([1, 2, 3])
>>> fs
frozenset({1, 2, 3})

Advantages

>>> fs.add(4)
Traceback (most recent call last):
AttributeError: 'frozenset' object has no attribute 'add'

>>> hash(fs)                    # hashable -- a regular set is NOT
-272375401224217160
>>> d = {fs: "value"}           # usable as a dict key
>>> d
{frozenset({1, 2, 3}): 'value'}

Use Cases

  • A fixed set of valid options that should never change at runtime
  • A set-of-sets, since a frozenset can be a member of another set
  • A dict key representing a group/combination of values

Quick Interview Answer

“frozenset is to set what a tuple is to a list: the same core behavior — union, intersection, membership — with mutation removed. That single change is what makes it hashable, and hashability is the whole payoff: a frozenset can be a dict key or a member of another set, both of which are flatly impossible for a regular set, since set.__hash__ doesn’t exist. The natural use case is a fixed group of values that itself needs to act like a value — a set-of-sets, or a dict key representing some combination.”

Common Mistakes

  • Trying fs.add(x) or fs.remove(x) on a frozenset — neither exists; AttributeError is raised immediately, the same shape of mistake as calling .append() on a tuple.
  • Reaching for a regular set as a dict key or set member and hitting TypeError: unhashable type: 'set' — swap in frozenset instead.
  • Assuming frozenset and tuple are interchangeable for “an immutable collection” — a frozenset still deduplicates and is unordered; a tuple preserves order and duplicates. Pick based on which behavior is actually needed.

Add More Questions to This Guide

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

Open Google Form