In this tutorial we will learn all about python frozenset() method and its uses.
What is python frozenset() Method?
The frozenset() method returns an immutable frozenset object like a regular set object but cannot be modified once declared. The frozenset() takes input as python iterable.
In Python, Frozenset is just like a normal python set object, but a python set is a mutable object. In the python set, we can modify each element and be added or removed, but in frozenset we cannot modify, add, or remove any element.
The syntax of frozenset() is:
The frozenset() method takes only one parameter:
- Iterable (optional) – the python iterable like a set, dictionary, tuple, etc., which contains elements.
Let’s check some examples of the python frozenset() method.
Example 1: How to use frozenset() in python?
We will get the following output.
As you can see in the above example, we are first creating a list of numbers and converting it into a frozenset. Also, you can see we are getting class frozenset when we check the type of the Fset. We are trying to add one more number to the Fset, but as we know, frozenset cannot modify it is showing as an error because there is no attribute to add or remove an element from python frozenset.
But there are different attributes available with frozenset().
Frozenset Operations in Python
Five operations can be performed in frozenset, just like regular sets.
Let see an example of how we can use operations in frozenset.
Example 2: How to use Python frozenset operations.
When we run the above program we will get the following output:
We can also use simple set operations like isdisjoint, issubset, and issuperset with the python frozenset.
Example 3: Using python set operations with frozenset.
Rules of frozenset()
- frozenset() only takes iterable as an argument.
- frozenset() method returns an immutable frozenset which the iterable elements will initialize.
- Empty frozenset can be declared bypassing the empty frozenset() method.