Sobes.tech
Junior

What is the purpose of frozenset in Python?

sobes.tech AI

Answer from AI

FrozenSet is an immutable set, similar to set, which cannot be modified after creation.

Main uses:

  • As dictionary keys: Regular sets are not hashable and cannot be used as keys. Frozenset is hashable and can be used as a key.
  • Elements of another set: A regular set cannot contain another mutable set as an element. Frozenset can.
  • Immutable data: If an immutable collection of unique elements is needed, frozenset guarantees that the data set will not change after creation. Useful for hash optimization and comparison.
# Example of using frozenset as a dictionary key
my_dict = {frozenset({1, 2, 3}): "value"}
print(my_dict[frozenset({1, 2, 3})])

# Example of using frozenset as an element of a set
my_set = {frozenset({1, 2}), frozenset({3, 4})}
print(my_set)