Frozenset in Python - Lokesh
Frozenset in Python - Lokesh
rozenset() in Python
Last Updated : 03 Jul, 2024
Python 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.
Example
In this example, we are creating a frozen set with the list in Python.
Python
Output
True
False
In this example, we are showing how to create a frozen set in Python and we are showing that frozen
set objects are immutable and can not be modified after the creation.
Python
https://www.geeksforgeeks.org/frozenset-in-python/ 1/5
11/12/24, 5:03 PM frozenset() in Python - GeeksforGeeks
Output
If no parameters are passed to frozenset() function, then it returns an empty frozenset type object
in Python.
Python
Output
Here as a parameter a list is passed and now its frozen set object is returned.
Python
https://www.geeksforgeeks.org/frozenset-in-python/ 2/5
11/12/24, 5:03 PM frozenset() in Python - GeeksforGeeks
Output
Since frozen set objects are immutable, they are mainly used as keys in dictionary or elements of
other sets. The below example explains it clearly.
Python
# creating a dictionary
Student = {"name": "Ankit", "age": 21, "sex": "Male",
"college": "MNNIT Allahabad", "address": "Allahabad"}
Output
If by mistake we want to change the frozen set object, then it throws a TypeError
Python
# creating a list
favourite_subject = ["OS", "DBMS", "Algo"]
https://www.geeksforgeeks.org/frozenset-in-python/ 3/5
11/12/24, 5:03 PM frozenset() in Python - GeeksforGeeks
# creating a frozenset
f_subject = frozenset(favourite_subject)
Output
Frozenset operations
Frozen sets are immutable sets that allow you to perform various set operations such as union,
intersection, difference, and symmetric difference.
Python
# initialize A and B
A = frozenset([1, 2, 3, 4])
B = frozenset([3, 4, 5, 6])
# copying a frozenset
C = A.copy()
print(C)
# union
union_set = A.union(B)
print(union_set)
# intersection
intersection_set = A.intersection(B)
print(intersection_set)
difference_set = A.difference(B)
print(difference_set)
# symmetric_difference
symmetric_difference_set = A.symmetric_difference(B)
print(symmetric_difference_set)
Output
https://www.geeksforgeeks.org/frozenset-in-python/ 4/5
11/12/24, 5:03 PM frozenset() in Python - GeeksforGeeks
frozenset({1, 2, 3, 4})
frozenset({1, 2, 3, 4, 5, 6})
frozenset({3, 4})
frozenset({1, 2})
frozenset({1, 2, 5, 6})
https://www.geeksforgeeks.org/frozenset-in-python/ 5/5