Last modified: Nov 15, 2026

Python Frozenset: A Complete Guide

A frozenset is an immutable version of a Python set. It holds unique items. But once created, it can never change.

That single rule makes frozensets useful in places where normal sets fail. They can be dictionary keys. They can live inside other sets. They are safe to share.

This guide covers creation, operations, use cases, and common mistakes. By the end, you will know exactly when to reach for a frozenset.

What Is a Frozenset?

A set is mutable. You can add items, remove items, and update it in place. A frozenset is the opposite. It is hashable and unchangeable.

Like a set, a frozenset stores unique elements. Duplicates are dropped automatically. Order is not guaranteed.

The key difference is immutability. You cannot call add() or remove() on a frozenset. Those methods simply do not exist.

How to Create a Frozenset

Use the built-in frozenset() constructor. It accepts any iterable, such as a list, tuple, string, or set.


# Create a frozenset from a list
fruits = frozenset(["apple", "banana", "apple", "cherry"])
print(fruits)
print(type(fruits))

frozenset({'apple', 'cherry', 'banana'})

Notice two things in the output. The duplicate "apple" appears only once. And the type is frozenset, not set.

You can also create an empty frozenset. Just call frozenset() with no arguments.


# Empty frozenset
empty = frozenset()
print(empty)
print(len(empty))

frozenset()
0

Remember that {} creates an empty dictionary, not a frozenset. The constructor is the only clean way to build an empty one.

Frozenset Is Immutable

Try to modify a frozenset and Python raises an error. This is the core behavior you must understand.


colors = frozenset(["red", "green"])

# This will fail
colors.add("blue")

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

The error is clear. There is no add() method. The same applies to remove(), discard(), pop(), and clear().

Immutability is not a limitation here. It is a feature. It guarantees the object stays the same for its whole life.

Frozenset as a Dictionary Key

Dictionary keys must be hashable. Normal sets are not hashable, so they cannot be keys. Frozensets are hashable, so they can.


# Use frozensets as dict keys
permissions = {
    frozenset(["read", "write"]): "editor",
    frozenset(["read"]): "viewer",
}

print(permissions[frozenset(["read", "write"])])

editor

This pattern is powerful. You can group items into unordered collections and still use them as lookup keys. If you are working with dictionaries often, our guide on checking if a key exists in a Python dictionary pairs well with this idea.

Note that key order does not matter. frozenset(["read", "write"]) equals frozenset(["write", "read"]). Both hash the same way.

Frozenset Inside a Set

Sets can only hold hashable items. That means you cannot nest a normal set inside another set. But you can nest frozensets.


# Nested frozensets inside a set
groups = {
    frozenset([1, 2]),
    frozenset([3, 4]),
    frozenset([1, 2]),  # duplicate, ignored
}

print(groups)
print(len(groups))

{frozenset({1, 2}), frozenset({3, 4})}
2

The duplicate is dropped. The outer set works because each inner frozenset is hashable. This is a common trick for grouping data.

If you are still deciding between sets and other collections, read Python set vs list: key differences for a quick comparison.

Set Operations on Frozensets

Frozensets support the same math-style operations as sets. The difference is that these operations return new frozensets. The originals stay untouched.

Union

Use union() to combine two frozensets. The result contains every unique item from both.


a = frozenset([1, 2, 3])
b = frozenset([3, 4, 5])

print(a.union(b))

frozenset({1, 2, 3, 4, 5})

Intersection

Use intersection() to get only the shared items.


a = frozenset([1, 2, 3])
b = frozenset([3, 4, 5])

print(a.intersection(b))

frozenset({3})

Difference

Use difference() to remove items found in the second frozenset.


a = frozenset([1, 2, 3])
b = frozenset([3, 4, 5])

print(a.difference(b))

frozenset({1, 2})

Symmetric Difference

Use symmetric_difference() to keep items that appear in only one of the two frozensets.


a = frozenset([1, 2, 3])
b = frozenset([3, 4, 5])

print(a.symmetric_difference(b))

frozenset({1, 2, 4, 5})

All four operations return new objects. None of them change a or b. That is the immutability promise in action.

Frozenset vs Set

The two types share the same API for reading. Membership tests, length checks, and comparisons all work the same way.

The difference is writing. Sets allow changes. Frozensets do not. Sets are unhashable. Frozensets are hashable.

Use a set when you need to grow or shrink a collection. Use a frozenset when the data is fixed and you need hashability.

When you build lookup structures from fixed collections, you may also need to flip keys and values. Our complete guide to inverting a Python dictionary shows how to do that safely.

Common Use Cases

Frozensets shine in a few practical spots. Here are the most common ones.

Dictionary keys. Group items into tuples of settings and use them as keys. Frozensets make the order irrelevant.

Constant sets. Define allowed values at module level. Nobody can accidentally mutate them.

Nested collections. Store sets inside sets, or sets inside dictionaries, without errors.

Function defaults. A frozenset makes a safe, shared default argument. Mutable defaults cause classic bugs.


# Safe default argument
def check_tags(tags=frozenset()):
    return len(tags)

print(check_tags())
print(check_tags(frozenset(["a", "b"])))

0
2

Converting Between Set and Frozenset

Conversion is simple and cheap. Pass a set to frozenset() to freeze it. Pass a frozenset to set() to unfreeze it.


mutable = {1, 2, 3}
frozen = frozenset(mutable)

print(type(frozen))

back = set(frozen)
back.add(4)
print(back)

{1, 2, 3, 4}

This pattern is handy. Keep data frozen by default. Unfreeze only when you truly need to change it.

Membership and Comparison

Checking membership works exactly like a set. Use the in keyword. It is fast, because sets and frozensets use hashing.


vowels = frozenset("aeiou")

print("a" in vowels)
print("z" in vowels)
print(vowels == frozenset(["a", "e", "i", "o", "u"]))

True
False
True

Comparison ignores order. Two frozensets are equal if they hold the same items. This makes them ideal for equality checks on unordered data.

If you often compare or sort dictionary data alongside sets, our guide on how to sort a Python dict by key will help you keep output predictable.

Common Mistakes

Beginners hit a few predictable errors with frozensets. Watch for these.

Calling mutating methods. There is no add() or remove(). Convert to a set first if you need to change things.

Assuming order. Frozensets have no guaranteed order. Do not rely on print output order.

Using a set as a key. Only frozensets are hashable. A plain set raises a TypeError as a dictionary key.

Forgetting the constructor. There is no literal syntax. You must write frozenset([...]).

Performance Notes

Frozensets have the same lookup speed as sets. Membership tests are O(1) on average. That is far faster than scanning a list.

Because they are immutable, they can be safely shared across threads. No locks are needed to read them.

They also use slightly less memory in some cases, since Python can optimize immutable containers. The difference is small, but it exists.

Frequently Asked Questions

Can a frozenset contain a list? No. Every item inside must be hashable. Lists are not hashable.

Can a frozenset contain another frozenset? Yes. That is one of its main advantages over a set.

Is a frozenset ordered? No. Like a set, it has no defined order.

Can I add items to a frozenset? No. Create a new one with union() or convert to a set.

Conclusion

A frozenset is a set that cannot change. That one property unlocks hashability, safe sharing, and nesting.

Use it for dictionary keys, constant collections, and function defaults. Use a regular set when you need to modify data over time.

Start with a simple rule. If a collection never changes, freeze it. Your code becomes safer, and your intent becomes clearer.

Practice with the examples above. Convert a few of your own sets to frozensets and see where they fit. The habit pays off quickly.