In Python, frozenset(iterable) creates an immutable set: it holds unique, hashable items like a set, but it has no add(), remove(), or other methods that change it.
Because it cannot change, a frozenset is hashable. That means it can be used as a dict key or stored inside another set, which a normal set cannot. Order does not matter: frozenset([1, 2]) == frozenset([2, 1]).
frozenset is a built-in type (a class) that you call like a function: each call creates a new frozenset object. Like every built-in, it lives in the builtins module and is always available without an import.
Syntax
Pass any iterable of hashable items.
python
fixed = frozenset(iterable)
empty = frozenset()
Call
What it does
frozenset("aab")
The unique letters a and b.
frozenset([1, 2]) == {1, 2}
True: equal to a set with the same items.
{frozenset([1, 2]): "x"}
A frozenset as a dict key.
a | b
Union; returns a new frozenset.
All read-only set operations work: |, &, -, ^, issubset(), in, and len().
Library declarations
python
frozenset(iterable=(), /)
# class frozenset: an immutable, hashable built-in type
Parameters
Parameter
Description
iterable
Optional. An iterable of hashable items. Default: empty.
Return Value
Return Value
Description
frozenset
A new immutable set with the unique items.
Python Examples
Example 1 — A Read-Only Set of Vowels
Create a frozenset, test membership, and try to add an item.
python
vowels = frozenset("aeiou")
print(len(vowels), "e" in vowels, "y" in vowels)
print(sorted(vowels))
try:
vowels.add("y")
except AttributeError:
print("frozenset has no add() method")
Output
5 True False
['a', 'e', 'i', 'o', 'u']
frozenset has no add() method
How It Works
Built from a string. Each vowel becomes one item of the frozenset.
Fast lookups.in works exactly as with a normal set.
Stable display.sorted() lists the vowels alphabetically, whatever the internal order.
No mutating methods.add is not defined, so Python raises AttributeError.
Example 2 — Order-Independent Dict Keys
Store distances between city pairs so that the order of the two cities does not matter.