frozenset
The frozenset data type in Python is a pre-defined class categorized as a Set Category Data Type.
- Stores multiple unique values (of the same or different types) in a single object.
- Duplicates are automatically removed, similar to a set.
- A frozenset is created using the frozenset() function, which accepts iterable inputs like lists, tuples, or sets
frozensetobj = frozenset({val1, val2, ..., val_n}) # From set
frozensetobj = frozenset([val1, val2, ..., val_n]) # From list
frozensetobj = frozenset((val1, val2, ..., val_n)) # From tuple
fs1 = frozenset([10, "Python", 20.5, True])
fs2 = frozenset({1, 2, 2, 3}) # Duplicates removed: {1, 2, 3}
fs3 = frozenset((4, 5, 6))
print(fs1) # frozenset({10, 'Python', 20.5, True})
print(fs2) # frozenset({1, 2, 3})
print(fs3) # frozenset({4, 5, 6})
- Unlike set (e.g., {1, 2, 3}), there is no direct literal notation for frozenset. It must be created using frozenset().
- A frozenset does not maintain insertion order, meaning elements may be displayed in any order.
- A frozenset is immutable, meaning its elements cannot be modified, added, or removed after creation.
- Since frozenset does not maintain insertion order, indexing and slicing operations are not supported.
- Any iterable (list, tuple, set, etc.) can be converted to a frozenset.
- Since frozenset is immutable, it can be more memory-efficient in scenarios where a fixed, unchangeable set of elements is needed.
fs = frozenset([1, 2, 3])
print(fs) # Could print: frozenset({1, 2, 3}) or frozenset({3, 1, 2}), etc.
fs = frozenset([1, 2, 3])
fs.add(4) # AttributeError: 'frozenset' object has no attribute 'add'
fs[0] = 5 # TypeError: 'frozenset' object does not support item assignment
fs = frozenset([1, 2, 3])
print(fs[0]) # TypeError: 'frozenset' object is not subscriptable
# frozenset itrable
lst = [1, 2, 3]
tup = (4, 5, 6)
st = {7, 8, 9}
fs1 = frozenset(lst) # frozenset({1, 2, 3})
fs2 = frozenset(tup) # frozenset({4, 5, 6})
fs3 = frozenset(st) # frozenset({7, 8, 9})
- Both set and frozenset store unique elements and support similar operations (e.g., union, intersection).
- set is mutable (supports add(), remove(), etc.) and immutable in some contexts (e.g., cannot modify elements directly).
- frozenset is strictly immutable (no modifications allowed).
s = {1, 2, 3}
s.add(4) # Works: s = {1, 2, 3, 4}
fs = frozenset([1, 2, 3])
fs.add(4) # Error: immutable
frozenset is useful when you need a set-like object that cannot be modified, such as:
- Keys in dictionaries (since dictionary keys must be immutable).
- Elements in other sets (since set elements must be immutable).