frozenset () in Python

Python Methods and Functions

In Python, frozenset is the same as set, except that its elements are immutable. This function takes input as any iterative object and converts it to an immutable object. Item order is not guaranteed to be preserved.

Syntax: frozenset (iterable_object_name)

Parameter: This function accepts iterable object as input parameter.

Return Type: This function return an equivalent frozenset object.

Below are examples that explain this clearly.

Example # 1:

If no parameters are passed to frozenset () , it returns an empty frozenset object.

# Python program for understanding the frozenset () function

 
# tuple of numbers

nu = ( 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 )

  
# convert tuple to frozenset

fnum = frozenset (nu)

  
# print details

print ( " frozenset Object is: " , fnum)

Exit :

 frozenset Obj ect is: frozenset ({1, 2, 3, 4, 5, 6, 7, 8, 9}) 

Example # 2: Using frozenset() .

Because Frozenset objects are immutable, they are mainly used as a key in a dictionary or elements of other collections. The example below explains this clearly.

# Python program to understand usage
# Frozenset functions

 
# create a dictionary

Student = { "name" : "Ankit" , " age " : 21 , "sex" : "Male"

"college" : "MNNIT Allahabad" , "address" : "Allahabad" }

 
# freeze dictionary keys

key = frozenset (Student)

 
# printing keys

print ( 'The frozen set is:' , key)

Exit:

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

Example # 3: Warning

If by mistake we want to change an object, it will throw the error" ".

# Python program to understand
# using the Frozenset function

 
# creating a list

favorite_subject = [ "OS" , "DBMS" , "Algo" ]

 
# make it freeze type

f_subject = frozenset (favorite_subject)

  
# below the line will give an error

  

f_subject [ 1 ] = " Networking "

Exit :

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




Get Solution for free from DataCamp guru