SyntaxStudy
Sign Up
Python Intermediate 9 min read

Frozensets

Frozensets

A frozenset is an immutable version of a set. Because it is hashable, it can be used as a dictionary key or as an element inside another set.

Creating Frozensets

fs = frozenset([1, 2, 3, 4, 4])
print(fs)   # frozenset({1, 2, 3, 4})
print(type(fs))  # frozenset

empty_fs = frozenset()

Read-Only Operations

print(3 in fs)         # True
print(len(fs))         # 4
print(fs | frozenset({5, 6}))  # union — returns new frozenset
print(fs & frozenset({2, 3}))  # intersection

Cannot Mutate

# fs.add(5)     # AttributeError
# fs.remove(1)  # AttributeError

As Dict Keys or Set Elements

# Sets of sets (impossible with mutable set)
s = {frozenset({1, 2}), frozenset({3, 4})}
print(s)

# As dict key
permissions = {
    frozenset({"read", "write"}): "editor",
    frozenset({"read"}):          "viewer",
}
user_perms = frozenset({"read", "write"})
print(permissions[user_perms])  # editor
Example
allowed = frozenset(["GET", "POST", "PUT"])
method = "DELETE"
if method not in allowed:
    print(f"{method} not permitted")

# Use as dict key
role_map = {frozenset(["read"]): "viewer", frozenset(["read","write"]): "editor"}
print(role_map[frozenset(["read"])])  # viewer
Pro Tip

Use frozenset when you need a set that will be used as a dictionary key, as a set element, or shared across threads without locking.