The frozenset() function in Python creates an immutable set from an iterable. It stores only unique values and does not allow modification after creation. Since it is immutable, a frozenset can be used as a dictionary key or as an element of another set.
Example: In this example, a frozenset is created from a list:
a = frozenset(["cat", "dog", "lion"])
print("cat" in a)
print("elephant" in a)
Output
True False
Explanation:
- frozenset([...]) creates an immutable set and "cat" in 'a' checks membership.
- Duplicate values (if any) are automatically removed.
Syntax
frozenset(iterable)
- Parameters: iterable - Any iterable object like list, tuple, set, string or dictionary.
- Return Value: Returns a frozenset object.
Examples
Example 1: In this example, a frozenset is created and tried to modify it to show that it is immutable.
f = frozenset(["apple", "banana", "orange"])
print(f)
f.add("grape")
Output
frozenset({'banana', 'apple', 'orange'})
Traceback (most recent call last):
File "c:\Users\gfg0753\test.py", line 4, in <module>
f.add("grape")
^^^^^
AttributeError: 'frozenset' object has no attribute 'add'
Explanation:
- frozenset([...]) creates an immutable set.
- f.add() is not allowed because frozenset cannot be modified.
Example 2: In this example, a frozenset is created from a tuple and a list to see how duplicates are handled.
a = ()
f1 = frozenset(a)
print(f1)
b = ["Geeks", "for", "Geeks"]
f2 = frozenset(b)
print(f2)
Output
frozenset()
frozenset({'Geeks', 'for'})
Explanation:
- frozenset(a) creates an empty frozenset.
- frozenset(b) removes duplicate "Geeks".
Example 3: Here, a dictionary is converted into a frozenset to observe what gets stored.
d = {"name": "A", "age": 21}
f = frozenset(d)
print(f)
Output
frozenset({'name', 'age'})
Explanation: frozenset(d) stores only dictionary keys. Values are not included in the frozenset.
Frozenset operations
A frozenset supports common set operations such as union, intersection, difference and symmetric difference. Although it is immutable, these operations return new frozenset objects without modifying the original sets.
a = frozenset([1, 2, 3, 4])
b = frozenset([3, 4, 5, 6])
c = a.copy()
print(c)
print(a.union(b))
print(a.intersection(b))
print(a.difference(b))
print(a.symmetric_difference(b))
Output
frozenset({1, 2, 3, 4})
frozenset({1, 2, 3, 4, 5, 6})
frozenset({3, 4})
frozenset({1, 2})
frozenset({1, 2, 5, 6})
Explanation:
- a.copy() creates a copy of a.
- a.union(b) combines elements of both sets.
- a.intersection(b) returns common elements.
- a.difference(b) returns elements only in a.
- a.symmetric_difference(b) returns elements that are not common to both sets.