Python Frozensets


Python frozensets are same as the set data type in Python the only difference is that frozensets are immutable which means you can’t add or remove the elements once it is created.

Frozensets are hashable and can be used as keys to a dictionary. In this article, you will learn python frozensets with some examples.

How to create a frozenset in Python

The frozensets() function is used to create frozensets in Python. Syntax of this function is given below –

frozenset(iterable_object_name)

Frozenset function takes the iterable object as an input parameter and returns an equivalent frozenset object.

For example –

x= frozenset([1,9,6,7,0,3])
y= frozenset([5,1,9,4,7,2])
# Now check the type of x and y
print(type(x))
print(type(y))

You can see the output in the given image –

Now if you try to add or remove elements from these frozensets it will through an error.

Set operations on frozensets

The Python frozenset supports various methods which includes union(), intersection(), difference(), symmetric_difference(), issubset(), isdisjoint(), etc.

You can perform various set operations on frozenset in Python.

For example –

print(f"Union of x and y is {x.union(y)}")
print(f"Intersection of x and y is {x.intersection(y)}")
print(f"x difference y is {x.difference(y)}")
print(f"Symmetric difference of x and y is {x.symmetric_difference(y)}")
print(f"Is x is subset of y {x.issubset(y)}")
print(f"x and y are disjoint set {x.isdisjoint(y)}")

You can see the output in the given image –

Conclusion

Now you can try other set operations on Python frozensets. If you have a query then leave it in the comments below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.