The frozenset() is an inbuilt function is Python which takes an iterable object as input and makes them immutable. Simply it freezes the iterable objects and makes them unchangeable.
In Python, frozenset is same as set except its elements are immutable. This function takes input as any iterable object and converts them into immutable object. The order of element is not guaranteed to be preserved.
Example #1:
If no parameters are passed to frozenset() function then it returns a empty frozenset type object.
# Python program to understand frozenset() function # tuple of numbers nu =(1,2,3,4,5,6,7,8,9)# converting tuple to frozenset fnum =frozenset(nu)# printing details print("frozenset Object is : ", fnum)
Since frozenset object are immutable they are mainly used as key in dictionary or elements of other sets. Below example explains it cle
Output:
The frozen set is: frozenset({'college', 'address', 'sex', 'age', 'name'})
Example #3: Warning
If by mistake we want to change the frozenset object then it throws an error “‘frozenset’ object does not support item assignment“.
Output:
Traceback (most recent call last): File "/home/0fbd773df8aa631590ed0f3f865c1437.py", line 12, in f_subject[1] = "Networking" TypeError: 'frozenset' object does not support item assignment
# creating a dictionary
Student = {"name": "Ankit", "age": 21, "sex": "Male",
"college": "MNNIT Allahabad", "address": "Allahabad"}
# making keys of dictionary as frozenset
key = frozenset(Student)
# printing keys details
print('The frozen set is:', key)
# Python program to understand
# use of frozenset function
# creating a list
favourite_subject = ["OS", "DBMS", "Algo"]
# making it frozenset type
f_subject = frozenset(favourite_subject)
# below line will generate error
f_subject[1] = "Networking"
a = frozenset((1,2,3,3))
b = (1,2,3,3)
print(a, b) # {1, 2, 3} / (1, 2, 3, 3)