This article will cover a guide on using the “frozenset” function in Python that returns a new frozenset type Python object. These objects are similar to set objects available in Python with some key differences. All code samples in this article are tested with Python 3.9.5 on Ubuntu 21.04.
About Frozensets
The frozenset function takes one argument of an iterable type Python object and returns a new frozenset type Python object. A frozenset type object is a hashable and immutable Python object whose elements are frozen or unchangeable throughout their lifetime. In contrast to a set type Python object whose elements can be changed any time, all items in a frozenset remain constant. The usage of frozensets can be best understood through examples. Some of them are explained below.
Creating a New Frozenset Object
To get a new frozenset type object, just supply any iterable type as the optional argument to the frozenset function. Here is a code sample:
fset = frozenset(l)
print (fset)
print (type(fset))
The first statement in the code defines a new list that is simply called “l”. Next, a new frozenset object is created by calling the frozenset function and supplying the list as an argument. After running the above code sample, you should get the following output:
<class 'frozenset'>
As you can see in the output, fset is a frozenset type object and it uses the curly braces syntax used by sets as well in Python. Frozensets contain unique items only as duplicates are not allowed, again very similar to the Python set type objects. Every frozenset type object is a Python set but vice versa is not true as the set items can be changed by calling some methods. Note that you can create an empty frozenset by calling the frozenset function without any argument.
You cannot Modify a Frozenset Once Created
As stated earlier, a frozenset type object has items that do not change during their lifetime. While you can use methods available for Python sets with frozenset type objects, an error is thrown if you attempt to use a method that changes the original frozenset object itself. Here is an example:
new_set = set(l)
new_set.remove(1)
print (new_set)
fset = frozenset(l)
fset.remove(1)
In the above code sample, there are two statements where the “remove” method of set type objects is called. While an item is successfully removed from “new_set“, an error is thrown when the remove method is called on “fset“. After running the above code sample, you should get the following output:
Traceback (most recent call last):
File "main.py", line 9, in <module>
fset.remove(1)
AttributeError: 'frozenset' object has no attribute 'remove'
Other similar methods like “add”, “pop”, “clear”, “discard”, and so on won’t work with forzensets.
Methods that Work with Frozensets
All Python set methods that do not modify items of a set work with frozenset type objects. So you can compare two frozensets for equalities or inequalities, iterate / loop through them, get common or unique elements between two frozensets, and so on. Below is an example showing some of the methods that work with frozensets.
fset2 = frozenset([3, 4, 5, 6])
print (fset1.intersection(fset2))
print (fset1.union(fset2))
print (fset1.difference(fset2))
print (len(fset1))
print (len(fset2))
The code is self explanatory. Some methods that do not change values of original frozensets have been called. These methods have been mainly used for comparing elements of two different frozensets. After running the above code sample, you should get the following output:
frozenset({1, 2, 3, 4, 5, 6})
frozenset({1, 2})
4
4
Some of the other methods that work with frozen sets are: “issubset”, “issuperset”, “symmetric_difference”, “copy”, and so on. Equality operators like “>”, “<“, “>=”, and “<=” also work with frozenset type objects.
Frozensets can be Converted to Other Iterable Types
You can convert frozenset type objects to other iterables by calling their main constructor. The code sample below shows conversion of frozenset type objects to list, tuple, and set type objects.
print (list(fset))
print (tuple(fset))
print (set(fset))
After running the above code sample, you should get the following output:
(1, 2, 3, 4)
{1, 2, 3, 4}
Frozenset Use Cases
As frozenset objects are nothing but unchangeable / immutable set type Python objects, you may wonder about their utility as sets can always be used in their place. The most obvious use case of frozensets is for declaring set type objects with unique elements without risk of accidentally changing them later in the code. Frozenset type objects can be used as dictionary keys while sets cannot be used for the same purpose. Since frozensets are hashable, they can be used within sets, while sets cannot be inserted in another set. Take a look at the code below:
s = {1, 2, fset}
print (s)
s = {1, 2, {4, 5}}
In the second statement, a frozenset has been added to a set during creation. In the last statement, a set type object is used inside another set. After running the above code sample, you should get the following output:
Traceback (most recent call last):
File "main.py", line 27, in <module>
s = {1, 2, {4, 5}}
TypeError: unhashable type: 'set'
As you can see in the output, forzensets can be added to other sets. On the other hand, adding a set to another set throws an error as sets accept only hashable type items.
Conclusion
Frozensets provide a way to create immutable sets. They accept only unique elements and are hashable type objects so they can be used within other Python objects that only accept hashable objects as their children.