205. Immutable Data Structures in Python
🔹 1. Creating an Immutable Set with frozenset
frozensetfs = frozenset([1, 2, 3, 4])
print(fs) # Output: frozenset({1, 2, 3, 4})
# Trying to modify will raise an error
fs.add(5) # AttributeError: 'frozenset' object has no attribute 'add'🔹 2. Using frozenset as a Dictionary Key
frozenset as a Dictionary Keymy_dict = {frozenset([1, 2, 3]): "Immutable Key"}
print(my_dict[frozenset([1, 2, 3])]) # Output: Immutable Key🔹 3. Eliminating Duplicate Sets in a List
🔹 4. Using frozenset for Fast Membership Testing
frozenset for Fast Membership Testing🔹 5. Creating an Immutable Dictionary (Using types.MappingProxyType)
types.MappingProxyType)🔹 6. Preventing Modification of a Dictionary at Runtime
🔹 7. Hashing frozenset for Use in Caching
frozenset for Use in Caching🔹 8. Using frozenset in Function Arguments to Ensure Immutability
frozenset in Function Arguments to Ensure Immutability🔹 9. Immutable Nested Dictionaries
🔹 10. Protecting Global Constants with Immutable Structures
Summary of Immutable Data Structures in Python
Last updated