Python Frozenset: Everything You Need to Know
By Rahul Singh
Updated on Jun 04, 2026 | 11 min read | 3.03K+ views
Share:
Looks like you're browsing from the
United StatesSome programs may not be available in your location
Some programs may not be available in your location
Switch to upGrad USAll courses
Certifications
More
By Rahul Singh
Updated on Jun 04, 2026 | 11 min read | 3.03K+ views
Share:
Table of Contents
A frozenset is a built-in Python collection that stores unique elements, just like a regular set, but with one important difference: it cannot be modified after creation. Once a frozenset is defined, you cannot add, remove, or update its elements, making it an immutable data structure.
This immutability makes frozensets useful when you need a collection of constant values that should remain unchanged throughout a program. They also support many standard set operations while offering additional benefits such as hashability, allowing them to be used as dictionary keys or elements of other sets.
In this blog, you will learn what a python frozenset actually is, how to create and use one, what operations work on it, and when to choose it over a regular set.
Transform your career with upGrad’s Data Science Course. Learn from industry experts, work on hands-on projects, and gain the skills top employer’s demand.
A python frozenset is an immutable, unordered collection of unique elements. "Immutable" means once you create it, you cannot add, remove, or change its elements. This is the main thing that separates it from a regular Python set.
Feature |
set |
frozenset |
| Mutable | Yes | No |
| Ordered | No | No |
| Allows duplicates | No | No |
| Hashable | No | Yes |
| Can be a dict key | No | Yes |
| Can be nested in a set | No | Yes |
The hashable property is what makes frozenset genuinely useful. Because a regular set can change, Python cannot hash it. A frozenset cannot change, so Python can hash it. This means you can use a frozenset as a dictionary key or as an element inside another set.
Also Read: Understand What Is Mutable And Immutable In Python
You should reach for frozenset when:
Creating a frozenset is straightforward. You use the built-in frozenset() function and pass it any iterable.
frozenset(iterable)
From a list:
fs = frozenset([1, 2, 3, 4])
print(fs)
# Output: frozenset({1, 2, 3, 4})
From a string:
fs = frozenset("hello")
print(fs)
# Output: frozenset({'h', 'e', 'l', 'o'})
Notice duplicates are removed automatically, just like in a regular set.
From a tuple:
fs = frozenset((10, 20, 30, 20))
print(fs)
# Output: frozenset({10, 20, 30})
Empty frozenset:
fs = frozenset()
print(fs)
# Output: frozenset()
Important: You cannot create a frozenset using curly braces {}. That syntax creates a regular set or a dictionary. Always use frozenset().
Also Read: 4 Built-in Data Structures in Python: Dictionaries, Lists, Sets, Tuples
permissions = {
frozenset(["read", "write"]): "editor",
frozenset(["read"]): "viewer"
}
user_role = frozenset(["read", "write"])
print(permissions[user_role])
# Output: editor
This works because frozenset is hashable. A regular set would raise a TypeError here.
Also Read: 16+ Essential Python String Methods You Should Know
Even though frozenset in Python is immutable, it supports a wide range of operations. You can compare frozensets, combine them, and find differences, just like with regular sets.
All standard set theory operations work on frozensets. These return a new frozenset and never modify the original.
Union (all elements from both):
a = frozenset([1, 2, 3])
b = frozenset([3, 4, 5])
print(a | b)
# Output: frozenset({1, 2, 3, 4, 5})
# Or using method:
print(a.union(b))
Intersection (elements common to both):
print(a & b)
# Output: frozenset({3})
print(a.intersection(b))
Difference (elements in a but not b):
print(a - b)
# Output: frozenset({1, 2})
print(a.difference(b))
Symmetric Difference (elements in either but not both):
print(a ^ b)
# Output: frozenset({1, 2, 4, 5})
print(a.symmetric_difference(b))
Also Read: String Methods Python
x = frozenset([1, 2])
y = frozenset([1, 2, 3])
print(x.issubset(y)) # True
print(y.issuperset(x)) # True
print(x.isdisjoint(frozenset([4, 5]))) # True
Because frozenset is immutable, these methods are not available:
Calling any of them raises an AttributeError.
fs = frozenset([10, 20, 30])
print(10 in fs) # True
print(len(fs)) # 3
for item in fs:
print(item)
You can iterate over a frozenset, check membership with in, and get its length with len().
Also Read: Understanding Python Data Types
This is the most common question people have when they first encounter frozenset. Understanding the difference between set and frozenset in Python helps you pick the right one every time.
Aspect |
set |
frozenset |
| Created using | set() or {} | frozenset() only |
| Can modify after creation | Yes | No |
| Can use as dict key | No | Yes |
| Can add to another set | No | Yes |
| Memory footprint | Slightly higher | Slightly lower |
| Use case | Dynamic collections | Fixed, hashable collections |
Regular set:
s = {1, 2, 3}
s.add(4)
print(s) # {1, 2, 3, 4}
Frozenset:
fs = frozenset([1, 2, 3])
fs.add(4) # AttributeError: 'frozenset' object has no attribute 'add'
Also Read: Mastering the Randint Python Function for Random Integer Generation
This is something only frozenset makes possible:
# Using frozenset as element inside a set
nested = {frozenset([1, 2]), frozenset([3, 4])}
print(nested)
# Output: {frozenset({1, 2}), frozenset({3, 4})}
# This would fail with regular sets:
# nested = {{1, 2}, {3, 4}} # TypeError: unhashable type: 'set'Use a set when your collection needs to change. Use a frozenset in Python when your collection is fixed and you need it to be hashable or protected from changes. There is no performance winner here. Both are fast. The choice is about intent and correctness.
Also Read: Functions in Python: Definition, Types, Syntax, and Usage Explained
Knowing the theory is good. Seeing how frozenset python works in real code is better. Here are four practical scenarios where frozenset genuinely helps.
ADMIN_PERMISSIONS = frozenset(["read", "write", "delete", "manage"])
EDITOR_PERMISSIONS = frozenset(["read", "write"])
VIEWER_PERMISSIONS = frozenset(["read"])
def can_delete(user_permissions):
return "delete" in user_permissions
print(can_delete(ADMIN_PERMISSIONS)) # True
print(can_delete(EDITOR_PERMISSIONS)) # False
Permissions are a perfect fit for frozenset. They should not change at runtime.
Also Read: Python Built-in Modules: Supercharge Your Coding Today!
cache = {}
def get_report(departments):
key = frozenset(departments)
if key not in cache:
cache[key] = f"Report for {sorted(departments)}"
return cache[key]
print(get_report(["sales", "finance"]))
print(get_report(["finance", "sales"])) # Same result, same cache hit
Since frozenset(["sales", "finance"]) equals frozenset(["finance", "sales"]), this cache works regardless of input order.
edges = {
frozenset(["A", "B"]),
frozenset(["B", "C"]),
frozenset(["A", "C"])
}
# Check if edge exists
print(frozenset(["A", "B"]) in edges) # True
print(frozenset(["B", "A"]) in edges) # True (same edge, order doesn't matter)
Also Read: Hash tables and Hash maps in Python
groups = [
frozenset([1, 2, 3]),
frozenset([3, 1, 2]),
frozenset([4, 5])
]
unique_groups = set(groups)
print(unique_groups)
# Output: {frozenset({1, 2, 3}), frozenset({4, 5})}
Duplicate groups are automatically removed because frozenset comparison ignores order.
Also Read: Python Classes and Objects [With Examples]
Once you are comfortable with the basics, a few extra details can save you time and bugs.
Two frozensets are equal if they contain the same elements, regardless of how they were created:
a = frozenset([1, 2, 3])
b = frozenset([3, 2, 1])
print(a == b) # True
s = {1, 2, 3}
fs = frozenset([1, 2, 3])
print(s == fs) # True
print(s | fs) # {1, 2, 3} (returns a regular set)
print(fs | s) # frozenset({1, 2, 3}) (returns a frozenset)
The type of the result depends on the left operand.
regular_set = {1, 2, 3}
frozen = frozenset(regular_set) # set to frozenset
back_to_set = set(frozen) # frozenset to set
print(type(frozen)) # <class 'frozenset'>
print(type(back_to_set)) # <class 'set'>
from typing import FrozenSet
def process_tags(tags: FrozenSet[str]) -> str:
return ", ".join(sorted(tags))
Using type hints makes your intent clear: this function expects an immutable collection of strings.
The python frozenset is a small but genuinely useful data type. Its defining trait is immutability. Because it cannot be changed after creation, Python can hash it. That makes it suitable for dictionary keys, set elements, and any place where you want a fixed, unmodifiable collection.
You now know how to create a frozenset, what operations it supports, how it compares to a regular set, and where it actually helps in real code. The difference between set and frozenset in Python comes down to one word: changeability. When you need to change your collection, use a set. When you need it to stay fixed and hashable, use frozenset.
Want personalized guidance on Python and Data Science and upskilling? Speak with an expert for a free 1:1 counselling session today.
A frozenset in Python is an immutable version of a regular set. Once created, its elements cannot be added, removed, or modified. It stores unique, unordered elements, just like a set, but it is hashable, which means it can be used as a dictionary key or as an element inside another set.
The main difference between set and frozenset in Python is mutability. A regular set can be modified after creation using methods like add() and remove(). A frozenset cannot be changed at all. Because of this, frozenset is hashable while set is not. This makes frozenset usable as a dictionary key, which a set cannot be.
No. Like a regular set, a frozenset automatically removes duplicate values. If you pass a list with repeated elements to frozenset(), only unique values are kept. For example, frozenset([1, 1, 2, 3]) gives frozenset({1, 2, 3}).
Yes. You can convert a frozenset to a list using list(frozenset_obj) and to a regular set using set(frozenset_obj). The conversion is straightforward and works like any other iterable-to-collection conversion in Python.
No. A frozenset is unordered, just like a regular set. The elements have no guaranteed order. This means you cannot access elements by index. If you need ordered, immutable storage, use a tuple instead.
Yes, this is one of the most practical uses of frozenset python. Because a frozenset is immutable and therefore hashable, Python can use it as a dictionary key. A regular set cannot be used as a dictionary key because it is mutable and not hashable.
Actually, frozenset has fewer methods than a regular set. It lacks all the mutation methods like add(), remove(), discard(), pop(), and update(). Both types share read-only operations like union(), intersection(), difference(), issubset(), and issuperset().
Python raises an AttributeError saying the frozenset object has no attribute add. Since frozenset is immutable, none of the mutation methods exist on it. If you need to "add" an element, you must create a new frozenset by combining the original with the new element using the union operation.
Yes. Since frozenset is hashable, it can be an element inside another frozenset or a regular set. This is how you create nested or grouped set structures in Python. Regular sets cannot be nested this way because they are not hashable.
Performance is very similar between the two. Frozenset may use slightly less memory because Python does not need to allocate space for mutation operations. For most use cases, the speed difference is negligible. Choose between them based on whether you need mutability, not performance.
Use the == operator. Two frozensets are equal if they contain exactly the same elements, regardless of the order they were created in. For example, frozenset([1, 2, 3]) == frozenset([3, 1, 2]) returns True. You can also compare a frozenset and a regular set this way, and the result will be True if they hold the same values.
49 articles published
Rahul Singh is an Associate Content Writer at upGrad, with a strong interest in Data Science, Machine Learning, and Artificial Intelligence. He combines technical development skills with data-driven s...
Start Your Career in Data Science Today