Python Glossary Русский

all Python 3Sets (set)term

frozenset — immutable set

frozenset

frozenset is the immutable version of set. It is hashable, so it can be a dictionary key or an item of another set.

Syntax

frozenset(iterable)

The point of frozenset is hashability: a set of sets or a set-shaped dict key is impossible with plain set, which raises TypeError: unhashable type: 'set'. There are no in-place mutators (no add, discard, pop, update), but comparison crosses the type boundary — frozenset({1, 2}) == {1, 2} is True. In mixed operations the left operand decides the result type: frozenset | set gives a frozenset, set | frozenset gives a set.

Examples

fs = frozenset([1, 2, 3])
print(fs)  # → frozenset({1, 2, 3})
try:
    fs.add(4)
except AttributeError as e:
    print(e)  # → 'frozenset' object has no attribute 'add'
d = {frozenset([1, 2]): 'pair'}
print(d[frozenset([2, 1])])  # → pair — ключ словаря, порядок не важен
s = {frozenset([1, 2]), frozenset([3, 4])}
print(len(s))  # → 2 — элемент множества
fs2 = frozenset([1, 2, 3])
fs3 = frozenset([2, 3, 4])
print(fs2 & fs3)  # → frozenset({2, 3})

See also

Open in the full glossarydocs.python.orgReport an inaccuracy