Skip to content
Related Articles

Related Articles

Improve Article

frozenset() in Python

  • Difficulty Level : Basic
  • Last Updated : 12 Aug, 2021

The frozenset() is an inbuilt function in 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 the same as set except the frozensets are immutable which means that elements from the frozenset cannot be added or removed once created. This function takes input as any iterable object and converts them into an immutable object. The order of elements is not guaranteed to be preserved.

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

Syntax : frozenset(iterable_object_name)
Parameter : This function accepts iterable object as input parameter.
Return Type: This function return an equivalent frozenset object.

Below examples explains it clearly.

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)
frozenset Object is :  frozenset({1, 2, 3, 4, 5, 6, 7, 8, 9})


Example #2: Uses of frozenset().
Since frozenset object are immutable they are mainly used as key in dictionary or elements of other sets. Below example explains it clearly. 


# Python program to understand use
# of frozenset function
# 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)
The frozen set is: frozenset({'sex', 'age', 'address', 'name', 'college'})


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“. 


# 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"


Traceback (most recent call last):
  File "/home/", line 12, in 
    f_subject[1] = "Networking"
TypeError: 'frozenset' object does not support item assignment


My Personal Notes arrow_drop_up
Recommended Articles
Page :