A frozen set in Python is a set whose values cannot be modified. This means that it is immutable, unlike a normal set. Frozen sets help serve as a key in dictionary key-value pairs.
How to create frozen sets?
Frozen sets can be obtained using the frozenset() method. This function takes any iterable items and converts it to immutable.
Example:
1
2
3 |
a={1, 2,5, 4.6, 7.8, 'r', 's'}
b=frozenset(a)
print(b) |
Output: frozenset({1, 2, 4.6, 5, 7.8, ‘r’, ‘s’})
The above output consists of set b which is a frozen version of set a.
Accessing Elements of a Frozen Set
Elements of a frozen set can be accessed by looping through it as follows:
Example:
1
2
3 |
b=frozenset([1, 2, 4.6, 5, 7.8, 'r', 's'])
for x in b:
print(x) |
Output:
1
2
4.6
5
7.8
s
The above output shows that using the for loop, all elements of the frozen set b have been returned one after the other.
Frozen sets are immutable, therefore, you cannot perform operations such as add(), remove(), update(), etc.