frozenset() is a built-in that creates an immutable, hashable set-like object from an iterable. It keeps the uniqueness and mathematical set operations of a regular set, but it does not provide methods that modify its contents.
Because a frozenset is immutable and hashable, it can be used where a regular mutable set cannot, such as a dictionary key or an element inside another set.
frozenset(iterable)The iterable can be a list, tuple, set, string or another iterable. Every element stored in the frozenset must itself be hashable.
values = [1, 2, 3, 2]
frozen = frozenset(values)
print(frozen)The duplicate 2 is stored only once. Printed order should not be treated as fixed.
frozen = frozenset({1, 2, 3})
frozen.add(4)This raises AttributeError because frozenset has no mutating add() method.
Item assignment also fails:
frozen = frozenset([1, 2, 3])
frozen[1] = 8This raises TypeError. A frozenset is also unordered, so positional assignment would not make sense.
my_tuple = (1, 2, 3)
frozen = frozenset(my_tuple)
print(frozen)The original tuple can still be rebound or extended independently; the frozenset remains unchanged.
my_tuple = (1, 2, 3)
frozen = frozenset(my_tuple)
my_tuple += (4, 5)
print(my_tuple)
print(frozen)Non-mutating set operations are supported and return new objects.
A = frozenset({1, 2, 3})
B = frozenset({3, 4, 5})
print(A | B)
print(A & B)
print(A - B)
print(A ^ B)As with regular sets, displayed order is not guaranteed.
permissions = {
frozenset({'read', 'write'}): 'editor',
frozenset({'read'}): 'viewer',
}
print(permissions[frozenset({'write', 'read'})])editorThis works because a frozenset is hashable. A regular set cannot be used as a dictionary key.
groups = {
frozenset({1, 2}),
frozenset({3, 4}),
}
print(len(groups))2set vs frozenset Top ↑| Feature | set | frozenset |
|---|---|---|
| Unique elements | Yes | Yes |
| Ordered/indexed | No | No |
| Mutable | Yes | No |
| Hashable object | No | Yes, when its elements are hashable |
| Can be a dictionary key | No | Yes |
| Can be an element of another set | No | Yes |
| Mutating methods such as add/remove | Yes | No |
frozenset, not fronzenset.frozenset does not make an unhashable nested value valid; its elements still need to be hashable.+ operator is not a set-union operator. Use | or union().A | B create a new frozenset; they do not mutate A.Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.