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()
In Python, a frozenset is an immutable version of a set. This means that once you create a frozenset, you cannot modify it by adding or removing elements. Frozensets are hashable and can be used as keys in dictionaries, unlike regular sets.
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 :
Return Type :
The frozenset() function returns an unchangeable frozenset object (which is like a set object, only unchangeable).
# list myList = [ 1, 2, 3, 4, 5, 5, 2 ] # list to frozenset() fList= frozenset(myList) print(fList) # tuple myTuple = ( 8, 9, 8, 7, 6, 6, 0 ) # 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 = [ 1, 2, 3, 4, 5, 5, 2 ] # 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
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment