In Python, frozenset is a built-in class that returns an immutable frozenset object, representing an unordered collection of unique elements.

frozenset is similar to set; the key difference is that frozenset elements cannot be modified, and frozenset objects are hashable, meaning they can be used as dictionary keys or elements of other set types, while regular set objects cannot.

frozenset Syntax

my_frozenset = frozenset(iterable)

Parameter:

  • iterable: An iterable object, such as a list, tuple, or set.

frozenset adds all unique elements from the iterable to the collection and returns an immutable frozenset object. If no iterable is specified, it returns an empty collection.

frozenset Examples

Can be used as dictionary keys because frozenset is hashable:

"""
# set cannot be used as dictionary keys
d = {
    { 1, 2, 3 } : "value"
}
"""
# frozenset can
d = {
    frozenset({ 1, 2, 3 }) : "value"
}

Iterating over frozenset:

fset = frozenset([1, 2, 3])
for i in fset:
    print(i)