Frozenset. In Python we have some immutable types. With immutable collections, we can simplify some logic in programs. An immutable thing is frozen in place.
With frozenset, we have an immutable set. We cannot add or remove elements. In every other way it is like a set. And because it cannot be changed, it can be used as a dictionary key.
A simple example. Here is an example that uses the frozenset keyword. We create an immutable set of strings (bird, plant and fish).
Tip A frozenset can be used where a set cannot. It can be a dictionary key or a set element itself.
# Create 3 frozensets.
colors1 = frozenset(["blue", "red"])
colors2 = frozenset(["orange", "black"])
colors3 = frozenset(["black", "white"])
# Create a frozenset of two frozensets.
possible = frozenset([colors1, colors2])
# This frozenset is included.
if colors1 in possible:
print("Possible:", colors1)
# This one is not.
if colors3 not in possible:
print("Not possible:", colors3)Possible: frozenset({'blue', 'red'})
Not possible: frozenset({'white', 'black'})
Unhashable error. A set cannot be hashed. So when we try to create a set of sets we will get an "objects are unhashable" error (a TypeError).
# This example will not compile.
example = {1, 2, 3}
example2 = {example, {5, 6, 7}}Traceback (most recent call last):
File "C:\programs\file.py", line 6, in <module>
example2 = {example, {5, 6, 7}}
TypeError: 'set' objects are unhashable
Here we have an immutable and hashable set. We can test a frozenset for the existence of other pairs—this is a fast way to search for multiple elements.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Apr 15, 2025 (edit).