Please login

Prime

Prepinsta Prime

Video courses for company/skill based Preparation

(Check all courses)
Get Prime Video
Prime

Prepinsta Prime

Purchase mock tests for company/skill building

(Check all mocks)
Get Prime mock

Python frozenset()

frozenset() in Python

 

In Python, frozenset is same as set except its elements are immutable. frozenset() is an inbuilt function is Python.

This function takes any iterable object as input parameter and converts them into immutable object.Simply it freezes the iterable objects and makes them unchangeable. Order of element may change.

Python frozenset()

Example :

frozenset() method freeze the list, and make it unchangeable:

# list of numbers
numList = [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]

# converting list to frozenset
fnum = frozenset(numList)

# fnum will contain
fnum=( { 1, 2, 3, 4, 5, 6, 7, 8, 9 } )

Syntax :


frozenset( iterable_object )


Return Type :

The frozenset() function returns an unchangeable frozenset object (which is like a set object, only unchangeable).


# list
myList = [ 1234552 ]

# list to frozenset()
fList= frozenset(myList)

print(fList)


# tuple
myTuple = ( 8987660 )

# tuple to frozenset()
fTuple= frozenset(myTuple)

print(fTuple)


# dictionary
myDict = { 1 : “Muskan”2 : “Komal”3 : “Ankita”4 : “Vaibhav”5 : “Simran” }

# dictionary to frozenset()
fKeys= frozenset(myDict.keys())
fValues= frozenset(myDict.values())

print(fKeys)
print(fValues)


Output :

frozenset({1, 2, 3, 4, 5})

frozenset({8, 9, 7, 6, 0})

frozenset({1, 2, 3, 4, 5})
frozenset({'Muskan', 'Vaibhav', 'Ankita', 'Simran', 'Komal'})

If we try to modify this frozenset() then error will occur.


# list
myList = [ 1234552 ]

# list to frozenset()
fList= frozenset(myList)

#modifying the frozenset()
fList[1] = 20
print(fList)


Output :

TypeError                                 Traceback (most recent call last)
      7 #modifying the frozenset()
----> 8 fList[1] = 20
      9 print(fList)
TypeError: 'frozenset' object does not support item assignment