In Python, a set is a collection of unique elements, and it can be modified by adding or removing elements. However, sometimes you may want to create a set that cannot be modified. This is where the "frozenset()" function comes into play. In this article, we will discuss the frozenset() function, its usage, and provide examples to illustrate its use.
The frozenset() function is a built-in function in Python that creates an immutable set, i.e., a set that cannot be modified. Once a frozenset is created, it cannot be modified. The syntax of the function is as follows:
|
frozen_set = frozenset(iterable)
|
The "iterable" argument is a collection of elements that will be used to create the frozenset. The elements in the frozenset must be hashable, i.e., they must be able to be hashed so that they can be added to the set.
Let's take a look at some examples to illustrate the usage of the frozenset() function.
Example 1: Creating a Frozenset
|
my_set = {1, 2, 3, 4, 5}
frozen_set = frozenset(my_set)
print(frozen_set)
|
|
frozenset({1, 2, 3, 4, 5})
|
|
frozen_set = frozenset(['a', 'b', 'c'])
my_dict = {frozen_set: 100}
print(my_dict[frozen_set])
|
|
100
|
|
set1 = {1, 2, 3}
set2 = {3, 4, 5}
frozen_set1 = frozenset(set1)
frozen_set2 = frozenset(set2)
union_set = frozen_set1.union(frozen_set2)
intersection_set = frozen_set1.intersection(frozen_set2)
print(union_set)
print(intersection_set)
|
|
frozenset({1, 2, 3, 4, 5})
frozenset({3})
|