Python Reference ยท Built-in Functions
Python frozenset() function
Reference for Python frozenset(): create an immutable, hashable set, use it as a dictionary key or set element, and apply set operations that return new frozensets.
frozenset() builds an immutable version of a set. It holds unique, hashable elements like a regular set, but you cannot add or remove items after creation. Because it never changes, it is hashable, so it can be used as a dictionary key or as an element of another set.
Reach for it when a collection of unique items must be a key, must be shared safely without copies, or should signal to readers that it never changes.
tags = frozenset(["a", "b", "a"]) print(sorted(tags)) # ['a', 'b']
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
frozenset() frozenset(iterable)
| Name | Description |
|---|---|
iterable |
Optional. Any iterable of hashable items. Duplicates are discarded. |
Return value: a new frozenset. With no argument, an empty one.
Raises: TypeError if the argument is not iterable or an item is not hashable (for example a list).
Usage notes
- No mutating methods.
add,remove,discard,pop,clearandupdatedo not exist. Operators such as|,&,-and^return new objects. - Result type follows the left operand.
frozenset | setgives afrozenset;set | frozensetgives aset. - Equality ignores type.
frozenset({1}) == {1}isTrue, but the two are different types and only the frozen one is hashable. - Elements must be hashable, so a frozenset can contain tuples and other frozensets but not lists or normal sets.
- No order. Do not rely on iteration order; use
sorted()when you print or compare in text form. - Literal syntax: none exists. Build one with
frozenset({...})orfrozenset([...]). - Set comprehension: wrap it:
frozenset(x for x in data if x). - Copying is free.
frozenset(fs)returns the same object when given a frozenset, since sharing is safe.