frozenset() in Python


This function helps in converting a mutable list to an immutable one. This is needed when we have declared a list whose items are changeable but after certain steps we want to stop allowing the elements in it to change. In such scenario, we apply the frozenset() function as shown below.

Syntax

Syntax: frozenset(iterable_object_name)

In the below example we take a list, change its element and print it. Then in the next step we apply the frozenset function, and try changing the element again. In the second step we get the error showing that the list can not be modified anymore.

Example

# Before applying forzenset()
some_days = ["Mom","Tue","Wed","Thu"]
# change element
some_days[2]="Fri"
print("some_days =",some_days)
# Apply frozenset()
fixed_days=frozenset(some_days)
print("fixed_days= ",fixed_days)
# Change element in frozenset
fixed_days[2]="Wed"

Output

Running the above code gives us the following result −

some_days = ['Mom', 'Tue', 'Fri', 'Thu']
Traceback (most recent call last):
fixed_days= frozenset({'Thu', 'Mom', 'Fri', 'Tue'})
File "/py3.py", line 14, in
fixed_days[2]="Wed"
TypeError: 'frozenset' object does not support item assignment
raja
Published on 08-Aug-2019 10:01:31
Advertisements