Python Built-in Function frozenset():
The frozenset() is an inbuilt function in Python that takes an iterable object as input and makes them immutable. In other words, it freezes the iterable objects, so we cannot make any changes to them. So, trying to change such an object results in a TypeError exception. Moreover, it may or may not preserve the order of elements.
Signature
The signature for the frozenset()
function is as shown below.
o=frozenset(iterable)
Parameters and return type
- Here, an iterable can be a list, a dictionary, a tuple, or a set.
- However, it returns an equivalent frozenset object.
Python Built-in Function frozenset Examples:
Example 1: In this case, let us take a list and tuple with numbers in it. We will make this list and a tuple immutable using the frozenset function. As we can see, if we try to update the list, it will raise an TypeError
exception.
#Initializing
t=(1,2,3,4)
l=[11,12,13,14]
#using frozenset function and printing
o = frozenset(t)
print("Converted tuple is ",o)
o = frozenset(l)
print("Converted list is ",o)
Output
Converted tuple is frozenset({1, 2, 3, 4})
Converted list is frozenset({11, 12, 13, 14})
Traceback (most recent call last):
File "main.py", line 8, in
o[2]=15
TypeError: 'frozenset' object does not support item assignment
Example 2: In this case, let us demonstrate the working of the frozenset function with a dictionary. When we pass a dictionary as a parameter to the frozenset function, we see that all the keys are frozen.
# Initializing
Student = {"name": "Ram", "age": 19, "location":"Mumbai"}
# making dictionary as frozenset
o= frozenset(Student)
# printing
print('The frozen set is:', o)
Output
The frozen set is: frozenset({'name', 'location', 'age'})
Example 3: We will not pass any parameter to the frozenset function in this example. So, it returns an empty frozenset type object.
#Initializing
s={1,2,3,4}
#Using frozenset and printing
o = frozenset()
print("Converted Set is ",o)
Output
Converted Set is frozenset()
Conclusion
The frozenset() function returns the immutable object of an iterable. However, if we try to modify their elements, it will raise a TypeError
exception.
References
Happy Learning 🙂