In this tutorial, we will learn about frozenset in Python with the help of examples.
We know that a set is mutable object in Python, which means we can easily add, update, and delete elements in the existing set object. We do not need to create a new set object every time to update it.
In contrast, Python language provides a new built-in data structure, which is, in all respects, exactly like a set, except that it is immutable set object.
It means that once formed it cannot be changed, as with a tuple. In other words, the elements of frozen set cannot be changed after creation. We can neither add additional elements to it, nor remove an element from it.
Thus, we can say that a forzenset is immutable, hashable, and unordered of collection of unique elements or objects. The immutability of frozen set makes it possible to be used as keys in the dictionaries as well as an element of another set.
How to create a Frozenset in Python?
Python language provides a built-in method named frozenset() that we use to create a frozenset object. The general syntax to create frozenset in Python is as:
frozenset([iterable])
In this syntax, the frozenset() method accepts only one parameter:
- iterable: This is an optional parameter that will comprehend elements to make the frozen set ready. Iterable can be tuple, set, dictionary, etc.
This method returns an immutable frozenset initialized with elements from the specified iterable. If we do not pass parameters, it returns an empty frozen set.
Python Frozenset Example
Let’s take some example program to understand the frozen set clearly.
Example 1:
# Python program to create a frozenset. # Creating a list of elements. my_list = ["Python", "Java", "C++", "C"] # Creating a frozenset object using frozenset() method. fset = frozenset(my_list) print(fset)
Output: frozenset({'Java', 'Python', 'C++', 'C'})
In this example, we have created a list of elements. Then, we have created a frozenset object by using frozenset() function and passed an iterable object list to this method. The frozenset() method converts the iterable list object into frozen set as a return type of this method.
Example 2:
# Creating a tuple of vowels. vowels = ('a', 'e', 'i', 'o', 'u') # Creating a frozenset object. fSet = frozenset(vowels) print('Frozen set:', fSet) print('Empty frozen set:', frozenset())
Output: Frozen set: frozenset({'a', 'u', 'i', 'o', 'e'}) Empty frozen set: frozenset()
Example 3: Iterating a frozen set.
# Python program to iterate over elements of frozenset. fset = frozenset([10, 20, 30, 40, 50]) print(type(fset)) # Iterating over elements of frozenset. print("Iterating frozenset: ") for x in fset: print(x)
Output: <class 'frozenset'> Iterating frozenset: 40 10 50 20 30
The frozenset() supports all the set methods provided by Python language except add(), remove(), and discard() because we cannot change the elements of frozenset.
Example 4:
# Python program to proof frozenset is immutable object. # Creating a set object. my_set = {10, 30, 50, 70} my_set.add(90) print(my_set) # Creating a frozenset object. fset = frozenset({10, 30, 50, 70}) fset.add(90) print(fset)
Output: {70, 10, 50, 90, 30} AttributeError: 'frozenset' object has no attribute 'add'
In this example, we have created a normal set of elements. Then, we have added a new element using 90 by using add() method. On the other hand, we have created a frozenset object of four elements using frozenser() function.
When we added a new element 90 to frozenset, it raises an AttributeError as shown in the output of the program. This shows that frozen set is an immutable object which cannot be altered after creation in the existing frozen set object.
Example 5:
Python does not allow to use set elements in the set, since they should be immutable. Look at the below example code.
x11 = set(['Python']) x21 = set(["Programming"]) x31 = set(["Language"]) # Using set elements in the set. x = {x11, x21, x31} print(x)
Output: TypeError: unhashable type: 'set'
Now we can do the same operation with frozenset in Python because the frozensets are an immutable objects. Let’s write a code for it.
Example 6:
x11 = frozenset(['Python']) x21 = frozenset(["Programming"]) x31 = frozenset(["Language"]) x = {x11, x21, x31} print(x)
Output: {frozenset({'Programming'}), frozenset({'Language'}), frozenset({'Python'})}
Frozenset() Implements in Python Dictionary
Moreover, it is possible to pass a dictionary as an iterable object inside the frozenset() method. In this case, the frozenset() method takes only keys from the dictionary and returns a frozen set that contains dictionary keys as its elements. Let’s take an example based on it.
Example 7:
my_dict = {1: "Mahika", 2: "Ivaan", 3: "Amit"} print(type(my_dict)) fset = frozenset(my_dict) print(type(fset)) # Displaying the frozenset content that contains dictionary keys. print(fset)
Output: <class 'dict'> <class 'frozenset'> frozenset({1, 2, 3})
Frozenset Operations
Like general sets, frozensets can also perform different set of mathematical operations such as union, intersection, difference, etc.
Example 8:
# Python program to perform the mathematical operations by frozenset. # Creating two frozensets. fset1 = frozenset([1, 2, 3, 4]) fset2 = frozenset([3, 4, 5, 6]) # Copying a frozenset. copy_fset = fset1.copy() print("Frozenset copy: ", copy_fset) # Union print("Union: ", fset1.union(fset2)) # Intersection print("Intersection: ", fset1.intersection(fset2)) # Difference print("Difference: ", fset1.difference(fset2)) # symmetric_difference print("Symmetric difference: ", fset1.symmetric_difference(fset2))
Output: Frozenset copy: frozenset({1, 2, 3, 4}) Union: frozenset({1, 2, 3, 4, 5, 6}) Intersection: frozenset({3, 4}) Difference: frozenset({1, 2}) Symmetric difference: frozenset({1, 2, 5, 6})
In the same way, we can also perform other set methods like isdisjoint, issubset, and issuperset with frozen sets.
Example 9:
# Python program to perform the mathematical operations by frozenset. fset1 = frozenset([1, 2, 3, 4]) fset2 = frozenset([3, 4, 5, 6]) fset3 = frozenset([5, 6]) # isdisjoint() method print(fset1.isdisjoint(fset3)) # Output: True # issubset() method print(fset3.issubset(fset2)) # Output: True # issuperset() method print(fset2.issuperset(fset3)) # Output: True
Output: True True True
When to use Frozenset?
You can use frozenset when you need to use a set with an immutable object.
In this tutorial, you have learned about frozenset in Python with the help of important examples. Hope that you will have understood the basic points of frozen set and practiced all example programs.
Thanks for reading!!!