Python Sets · Lesson 62 of 149

Python frozenset

What you will learn

  • What a frozenset is, and how it differs from a set
  • Which operations work, and what type they return
  • Using a frozenset as a dictionary key and as a member of a set
  • Sets of sets, and a powerset
  • Practical uses: edges, groups and constants

1. A set that cannot change

A frozenset is the immutable version of a set. It has the same unique items, no order and no index, but once it is made, it cannot be changed. Because it cannot change, it is hashable (lesson 9.7), so it can go where a set cannot: as a dictionary key, or as an item of another set.

f = frozenset([3, 1, 2, 3])
print(f)
print(sorted(f), len(f), 2 in f)
print(frozenset(), frozenset("aab") == frozenset("ba"))
frozenset({1, 2, 3})
[1, 2, 3] 3 True
frozenset() True

You create it with frozenset(collection), and there is no literal for it (curly brackets always make a set). frozenset() is the empty one. It supports len, in, loops, min, max, sorted and equality, just like a set.

Quick check: why can a `frozenset` be a dictionary key but a `set` cannot?

A set can change, so it has no stable hash. A frozenset never changes, so it can be hashed.

2. What it cannot do

Every method that changes a set is missing:

Missing Error
add, remove, discard, pop, clear, update AttributeError: 'frozenset' object has no attribute 'add'
f = frozenset([3, 1, 2])
f.add(4)
AttributeError: 'frozenset' object has no attribute 'add'

Note that f |= {5} does not fail: |= falls back on f = f | {5}, which makes a new frozenset and moves the name to it (lesson 2.6). The old one is untouched.

3. Operations that work

The operations that make a new set all work (lesson 10.2): |, &, -, ^, union, intersection, difference, symmetric_difference, and the tests <=, issubset, isdisjoint and so on. The result is a new frozenset:

f = frozenset([3, 1, 2])
g = frozenset([2, 3, 4])
print(sorted(f | g), sorted(f & g), sorted(f - g), sorted(f ^ g))
print(type(f | g).__name__, f <= g, f.isdisjoint({9}))
[1, 2, 3, 4] [2, 3] [1] [1, 4]
frozenset False True

Mixing set and frozenset

When you combine a set with a frozenset, the result has the type of the left operand:

s = {1, 2}
print(type(s | f).__name__)
print(type(f | s).__name__)
print(type(s & f).__name__, type(f & s).__name__)
print(s == frozenset({1, 2}))
set
frozenset
set frozenset
True

A set and a frozenset with the same items are equal, and they have the same elements for all tests; only mutability differs.

set frozenset
written {1, 2} or set(...) frozenset(...)
can change yes no
hashable no yes
dictionary key no yes
member of a set no yes

To get a changeable copy from a frozenset, call set(f). To freeze a set, call frozenset(s):

ss = set(f)
ss.add(99)
print(sorted(ss), sorted(f))
[1, 2, 3, 99] [1, 2, 3]

4. As a dictionary key

d = {frozenset({1, 2}): "pair", frozenset({"a"}): "letter"}
print(d[frozenset([2, 1])])
print(d.get(frozenset({"a"})))
pair
letter

The order does not matter: frozenset([2, 1]) finds the key made from {1, 2}, because the two are equal and have the same hash (lesson 9.7). Using a plain set as the key is an error:

d[{1, 2}]
TypeError: unhashable type: 'set'

A frozenset key is the right choice when the combination of items matters but not its order, for example a pair of friends, a set of ingredients, or the inputs of a function whose order is irrelevant.

5. Sets of sets

A set cannot hold other sets, but it can hold frozensets:

sos = {frozenset({1, 2}), frozenset({2, 1}), frozenset({3})}
print(len(sos))
print(sorted(map(sorted, sos)))
2
[[1, 2], [3]]

frozenset({1, 2}) and frozenset({2, 1}) are equal, so they count as one item. The items of a frozenset must themselves be hashable, so a frozenset of plain sets fails (TypeError: unhashable type: 'set'), but a frozenset of frozensets works.

A powerset

The powerset of a collection is the set of all its subsets, including the empty one and the whole. With frozensets, it can be a real collection:

from itertools import chain, combinations

def powerset(iterable):
    items = list(iterable)
    return [frozenset(c)
            for c in chain.from_iterable(combinations(items, r) for r in range(len(items) + 1))]

ps = powerset([1, 2, 3])
print(len(ps))
print([sorted(p) for p in ps])
8
[[], [1], [2], [3], [1, 2], [1, 3], [2, 3], [1, 2, 3]]

Three items have 2 ** 3 = 8 subsets. (combinations and chain are from itertools, lesson 17.4.)

6. Practical uses

Undirected edges

An edge between A and B in an undirected graph is the same as one between B and A. A frozenset of the two ends ignores the order:

edges = {frozenset({"A", "B"}), frozenset({"B", "C"})}
print(frozenset({"B", "A"}) in edges)
print(frozenset({"A", "C"}) in edges)
print(len(edges))
True
False
2

Grouping by a combination

Words with the same letters can be grouped using a frozenset or a sorted string as the key. Take care, though:

words = ["listen", "silent", "enlist", "google", "gogole", "cat", "act"]

groups = {}
for w in words:
    groups.setdefault("".join(sorted(w)), []).append(w)
print(list(groups.values()))

print(frozenset("aab") == frozenset("ab"))
[['listen', 'silent', 'enlist'], ['google', 'gogole'], ['cat', 'act']]
True

The sorted-letters key keeps repeated letters, so it is a correct anagram test. A frozenset of letters drops repeats, so it wrongly treats "aab" and "ab" as the same. Choose the key to match what "same" means: here, a Counter or a sorted string keeps the counts, and a frozenset does not.

Constants and caches

A frozenset is a good fixed collection that no other code can change by accident, and a good cache key for a function whose argument order does not matter:

CONSTANT = frozenset({"read", "write"})
print("read" in CONSTANT, sorted(CONSTANT | {"exec"}))

cache = {}
def total_for(items):
    key = frozenset(items)
    if key not in cache:
        cache[key] = sum(key)
    return cache[key]

print(total_for([1, 2, 3, 3]), total_for([3, 2, 1]), len(cache))
True ['exec', 'read', 'write']
6 6 1

The cache holds one entry, because both calls have the same set of numbers. Notice that the duplicate 3 was dropped, so this total_for adds each different number once; it is a design choice that suits "sum of distinct values".

7. In a dataclass and as a field

Frozen dataclasses (lesson 13.11) are hashable only if all their fields are hashable, so a frozenset field works, but a set field does not:

from dataclasses import dataclass

@dataclass(frozen=True)
class Group:
    members: frozenset

print(Group(frozenset({1, 2})) == Group(frozenset({2, 1})))
True

Worked example: who can talk to whom

A chat app records conversations as pairs of users. Count the different conversations, and check if two users have one, ignoring who is first.

messages = [("Rina", "Sam"), ("Sam", "Rina"), ("Lee", "Mia"), ("Rina", "Sam"), ("Sam", "Lee")]

chats = {frozenset(pair) for pair in messages}
print(len(messages), len(chats))

def talked(a, b):
    return frozenset({a, b}) in chats

print(talked("Mia", "Lee"), talked("Rina", "Lee"))

count = {}
for pair in messages:
    key = frozenset(pair)
    count[key] = count.get(key, 0) + 1
busiest = max(count, key=count.get)
print(sorted(busiest), count[busiest])
5 3
True False
['Rina', 'Sam'] 3
Step Why a frozenset
frozenset(pair) ("Rina", "Sam") and ("Sam", "Rina") become the same key
a set of them removes repeated conversations: 5 messages, 3 different chats
talked(a, b) the order of the two names does not matter
a dictionary of counts frozensets are hashable, so they can be keys

The users and messages are made up.

Common mistakes

  • Looking for a literal. Curly brackets make a set; write frozenset(...).
  • Trying to change a frozenset with add or remove.
  • Putting a plain set inside a set or as a dictionary key. Freeze it first.
  • Using a frozenset of letters as an anagram key, which loses repeated letters.
  • Forgetting that mixed operations take the type of the left operand.

Key takeaways

  • A frozenset is an immutable, hashable set: made with frozenset(items), with no methods that change it.
  • All the non-changing set operations work and return a frozenset (the type of the left operand when mixed with a set).
  • It can be a dictionary key or a member of a set, so you can build sets of sets.
  • It ignores order and repeats, which makes it ideal for undirected pairs and combinations, and wrong when repeats matter.
  • Convert with set(f) to change, and frozenset(s) to freeze.

Practice

1. How do you make a frozenset of the letters of "hello"?

Show answer

frozenset("hello") gives frozenset({'h', 'e', 'l', 'o'}) (in some order).

2. What error does frozenset({1, 2}).add(3) give?

Show answer

AttributeError: 'frozenset' object has no attribute 'add'.

3. What type is {1} | frozenset({2}), and what type is frozenset({2}) | {1}?

Show answer

set and frozenset. The result takes the type of the left operand.

4. Why does {{1, 2}, {3}} fail, and how do you fix it?

Show answer

A set cannot hold sets, which are unhashable. Use frozensets: {frozenset({1, 2}), frozenset({3})}.

5. Write a key that treats the pairs ("a", "b") and ("b", "a") as the same.

Show answer

frozenset(("a", "b")), which equals frozenset(("b", "a")).

6. How many subsets does a set of 4 items have?

Show answer

2 ** 4 = 16, including the empty set and the full set.