Lesson 48 +10 XP

Frozenset

Frozenset

A frozenset is an unchangeable set. Make it, and you can't add or remove items.

Create a frozenset

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

What you can't do

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

Frozensets have no add, remove, or update.

What you can do

  • Membership tests: 3 in fs
  • Looping: for x in fs
  • The set math: union(), intersection(), difference(), symmetric_difference()
a = frozenset([1, 2])
b = frozenset([2, 3])
print(a.union(b))  # frozenset({1, 2, 3})

Why use a frozenset?

  • It's hashable, so it can be a dictionary key or live inside a set.
  • It protects data from accidental changes.

TL;DR

  • frozenset(iterable) makes an unchangeable set.
  • No add, remove, or update.
  • Membership, loops, and set math still work.
  • Because it's hashable, it can be a dict key.