creation
frozenset
Built-in that constructs an immutable, hashable set. Because it is hashable, a frozenset can be a dict key or an element of another set.
frozenset(iterable=()) Parameters
| Parameter | Purpose |
|---|---|
| iterable | Optional iterable of hashable elements; defaults to empty |
| returns | A new frozenset object |
Examples
>>> frozenset([1, 2, 2, 3])
frozenset({1, 2, 3}) Duplicates collapse just like a regular set.
>>> fs = frozenset({1, 2})
>>> fs.add(3)
AttributeError: 'frozenset' object has no attribute 'add' No mutating methods — it is immutable.
>>> s = {frozenset({1, 2}), frozenset({3, 4})}
>>> len(s)
2 frozensets can be elements of a set; plain sets cannot.
>>> frozenset({1, 2}) | frozenset({2, 3})
frozenset({1, 2, 3}) Supports the same read-only operators as set.
Gotcha
frozenset has no add/remove/update/pop/clear — mutation is not allowed. Use it when you need a set-typed dict key, a set element, or a defensively immutable value.
Related methods
set.add
Adds a single hashable element to the set in place. If the element is already present, the set is unchanged (no error).
set.union
Returns a NEW set containing every element that appears in s or any of the arguments. The method accepts any iterable(s); the | operator requires all operands to be sets or frozensets.
← All Python set methods · List methods · list vs tuple vs set