Skip to main content

Python frozenset

A frozenset is an immutable set: it can never be modified.

Its elements are unique, unordered and unchangeable, as in a regular set.

But you can never add or remove them.


Creating a frozenset

Pass any iterable to the frozenset() constructor to get a frozenset.

Example

Build a frozenset and check its type:

Prompt
Write a Python program that demonstrates the code shown in the PromptCookbook example. x = frozenset({"apple", "banana", "cherry"}) print(x) print(type(x))
Output: complete Python program

Frozenset Methods

So adding and removing elements is out. Every set operation that leaves the data untouched still works, though.

main.py
# Frozenset Methods
# Method        Shortcut    Description
# copy()                    Returns a shallow copy
# difference()  -           Returns a new frozenset with the difference
# intersection() &          Returns a new frozenset with the intersection
# isdisjoint()              Returns True if there is NO intersection between two frozensets
# issubset()    <= / <      Returns True if this frozenset is a (proper) subset of another
# issuperset()  >= / >      Returns True if this frozenset is a (proper) superset of another
# symmetric_difference() ^  Returns a new frozenset with the symmetric differences
# union()       |           Returns a new frozenset containing the union