Technical skill practice

Python Set of Sets: Use frozenset for Hashable Members

A mutable set cannot be an element of another Python set because set elements need to be hashable. Use frozenset when an inner collection should have set-style equality and membership while remaining immutable. The outer set can still be mutable unless you also make it a frozenset.

Start with a small, explicit task

Deduplicate fictional two-person teams where member order does not matter. First observe why directly nesting a mutable set fails. Then use immutable inner teams and add another team to the outer collection. Sort only for stable display; set ordering is not the task.

Run the complete example

This original example was checked with Python 3.12.14. Save it as python_set_of_sets.py and run it with Python 3.12. It uses only the standard library. The assertions check the stated results.

Expected output

mutable inner set rejected

[['Ada', 'Bo'], ['Cy', 'Dee']]

try:
    {set(["Ada", "Bo"])}
except TypeError:
    failure = "mutable inner set rejected"
else:
    raise AssertionError("expected unhashable set")
teams = {frozenset(["Ada", "Bo"]), frozenset(["Bo", "Ada"])}
assert len(teams) == 1
assert frozenset(["Ada", "Bo"]) in teams
teams.add(frozenset(["Cy", "Dee"]))
assert len(teams) == 2
display = sorted(sorted(team) for team in teams)
assert display == [["Ada", "Bo"], ["Cy", "Dee"]]
print(failure)
print(display)

Explain the result

The first expression raises TypeError because its proposed element is a mutable set. The frozenset versions of Ada/Bo compare equal regardless of their input order, so the outer set contains one team rather than two. This fits the stated unordered team-membership rule.

Adding Cy/Dee changes the outer set to two teams. That does not mutate either existing inner frozenset; each inner membership remains fixed. The final nested sorting is a presentation step that makes expected output deterministic without claiming a stable iteration order for ordinary sets.

Avoid these mistakes

Every element inside a frozenset must also be hashable. Wrapping a list of mutable sets in frozenset does not recursively convert those inner sets for you. If order or duplicates are meaningful within a group, a set-style representation is the wrong model; choose a structure that preserves those facts.

Questions, answered

Can an ordinary set contain another set?

Not as a direct element. The checked expression raises TypeError for the mutable inner set.

Does frozenset make the outer set immutable?

No. This example adds another inner frozenset to the still-mutable outer set.

Sources and examples

ResumizeAI team. Examples are fictional teaching material, not customer results. Replace sample details with your own facts.

Your experience. A complete resume.

Build in Resumize with ATS-friendly templates, guided editing and a live preview. Start free, then upgrade when you need more.

Free account required. Free-plan PDF exports include a watermark.