Skip to content
Related Articles

Related Articles

frozenset() in Python

Improve Article
Save Article
  • Difficulty Level : Basic
  • Last Updated : 07 Sep, 2022
Improve Article
Save Article

Python frozenset() Method creates an immutable Set object from an iterable. It is a built-in Python function. As it is a set object therefore we cannot have duplicate values in the frozenset.

frozenset() in Python

Syntax : frozenset(iterable_object_name)
Parameter : iterable_object_name

  • This function accepts iterable object as input parameter.

Return :  Returns an equivalent frozenset object.

Using frozenset() Method on tuple

If no parameters are passed to frozenset() function, then it returns an empty frozenset type object in Python.  

Python3




# passing an empty tuple
nu = ()
 
# converting tuple to frozenset
fnum = frozenset(nu)
 
# printing empty frozenset object
print("frozenset Object is : ", fnum)

Output:

frozenset Object is :  frozenset()

Using frozenset() Method on list

Here as a parameter a list is passed and now it’s frozenset object is returned.

Python3




l = ["Geeks", "for", "Geeks"]
  
# converting tuple to frozenset
fnum = frozenset(l)
  
# printing empty frozenset object
print("frozenset Object is : ", fnum)

Output:

frozenset Object is :  frozenset({'Geeks', 'for'})

Using frozenset() Method on Dictionary

Since frozenset objects are immutable, they are mainly used as key in dictionary or elements of other sets. The below example explains it clearly. 

Python3




# 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 dict keys as frozenset
print('The frozen set is:', key)

Output:

The frozen set is: frozenset({'address', 'name', 'age', 'sex', 'college'})

Exceptions while using Python frozenset() method

If by mistake we want to change the frozenset object, then it throws a TypeError

Python3




# creating a list
favourite_subject = ["OS", "DBMS", "Algo"]
 
# creating a frozenset
f_subject = frozenset(favourite_subject)
 
# below line will generate error
f_subject[1] = "Networking"

Output: 

TypeError                                 Traceback (most recent call last)
Input In [13], in <cell line: 8>()
      5 f_subject = frozenset(favourite_subject)
      7 # below line will generate error
----> 8 f_subject[1] = "Networking"

TypeError: 'frozenset' object does not support item assignment

My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!