The frozenset type was introduced in Python as an immutable version of the standard set type. It was important to ensure that sets could be used as elements of other sets and as keys of dictionaries — hence the need for an immutable variant.
The practical task is to require uniqueness and the ability to quickly check membership, as well as to use a set as a key in a dictionary or an element of another set. A regular set is not suitable, as it is mutable and, accordingly, not hashable.
frozenset is an immutable set. Once created, its elements cannot be changed: added, removed, or modified. However, frozenset supports all the same operations as set, except for the mutating ones.
fs = frozenset([1, 2, 3]) print(2 in fs) # True # fs.add(4) # AttributeError: 'frozenset' object has no attribute 'add' map_dict = {fs: 'frozen'} # Allowed, as frozenset is hashable
Can frozenset contain mutable objects (e.g., a list)?
No, only hashable/immutable objects can be elements of a set of any type. frozenset([[], 1]) will raise TypeError, just like a regular set.
Can a mutable set be obtained from a frozenset and back?
Both types can be converted into each other using standard constructors:
fs = frozenset([1,2,3]) s = set(fs) print(type(s)) # <class 'set'>
Does frozenset support the methods add() or remove()?
No, these methods are absent; any attempt to call them will result in an AttributeError, as frozenset is immutable.
Using a regular set as a key in a dict:
s = set([1, 2]) d = {s: 'value'} # TypeError: unhashable type: 'set'
Pros:
Cons:
Converting to frozenset:
fs = frozenset([1, 2]) d = {fs: 'value'} # OK print(d[frozenset([1, 2])]) # 'value'
Pros:
Cons: