Frozenset
What is a Frozenset?
A frozenset in Python is an immutable version of a set. This means once a frozenset is created, its elements cannot be changed, added, or removed. It's created using the frozenset() function.
Creating a Frozenset
Python
my_frozenset = frozenset([1, 2, 3, "apple"])
Key Characteristics
- Immutable: Elements cannot be added, removed, or modified once created.
- Unordered: Like sets, frozensets do not maintain a specific order of elements.
- Unique elements: Duplicate elements are automatically removed.
- Hashable: Frozensets can be used as dictionary keys due to their immutability and hashability.
Use Cases
- Dictionary keys: Since frozensets are immutable and hashable, they can be used as dictionary keys.
- Set operations: Frozensets support set operations like union, intersection, difference, and symmetric difference.
- Constant data: When you have data that should not be modified, frozensets can be used to ensure data integrity.
Example
Python
my_frozenset = frozenset([1, 2, 3])
print(my_frozenset) # Output: frozenset({1, 2, 3})
# Trying to modify (will raise an error)
# my_frozenset.add(4) # AttributeError: 'frozenset' object has no attribute 'add'
# Set operations
set1 = {1, 2, 3, 4}
intersection = set1 & my_frozenset
print(intersection) # Output: frozenset({1, 2, 3})
Comparison with Sets
Feature |
Set |
Frozenset |
Mutability |
Mutable |
Immutable |
Use as dictionary key |
No |
Yes |
Performance |
Generally faster |
Slightly slower due to immutability |
In essence, frozensets provide a way to create unmodifiable sets, which can be useful in various scenarios where data integrity is crucial.