205. Immutable Data Structures in Python

🔹 1. Creating an Immutable Set with frozenset

  • frozenset is an immutable version of set.

fs = 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'

🔍 How it works:

  • Unlike set, frozenset cannot be modified after creation.


🔹 2. Using frozenset as a Dictionary Key

  • Since frozenset is hashable, it can be used as a dictionary key.

my_dict = {frozenset([1, 2, 3]): "Immutable Key"}
print(my_dict[frozenset([1, 2, 3])])  # Output: Immutable Key

🔍 How it works:

  • Normal sets (set) can’t be dictionary keys, but frozenset can because it's hashable.


🔹 3. Eliminating Duplicate Sets in a List

  • Use frozenset to remove duplicate sets.

🔍 How it works:

  • set treats frozenset({1,2,3}) and frozenset({3,2,1}) as the same object, removing duplicates.


🔹 4. Using frozenset for Fast Membership Testing

  • Checking membership in a frozenset is faster than a list.

🔍 How it works:

  • Lookups in frozenset are O(1) (constant time) compared to O(n) for lists.


🔹 5. Creating an Immutable Dictionary (Using types.MappingProxyType)

  • Python doesn’t have a built-in immutable dictionary, but MappingProxyType makes it read-only.

🔍 How it works:

  • MappingProxyType makes a dictionary read-only, preventing modifications.


🔹 6. Preventing Modification of a Dictionary at Runtime

  • Use MappingProxyType to protect a dictionary after creation.

🔍 How it works:

  • The original dictionary can be changed, but the proxy cannot be modified directly.


🔹 7. Hashing frozenset for Use in Caching

  • frozenset can be used as a cache key because it's hashable.

🔍 How it works:

  • frozenset ensures that {1,2,3} and {3,2,1} are treated as the same cache key.


🔹 8. Using frozenset in Function Arguments to Ensure Immutability

  • Prevent accidental modifications to function arguments.

🔍 How it works:

  • This ensures that items cannot be modified inside process_items().


🔹 9. Immutable Nested Dictionaries

  • Use frozenset inside a dictionary to make nested data immutable.

🔍 How it works:

  • Ensures that both lists and dictionaries inside are immutable.


🔹 10. Protecting Global Constants with Immutable Structures

  • Prevents accidental modifications in large programs.

🔍 How it works:

  • The dictionary holding configuration settings cannot be modified after creation.


Summary of Immutable Data Structures in Python

Snippet
Description

1️⃣

Creating frozenset

2️⃣

Using frozenset as a dictionary key

3️⃣

Removing duplicate sets using frozenset

4️⃣

Fast membership testing with frozenset

5️⃣

Creating an immutable dictionary with MappingProxyType

6️⃣

Protecting dictionary values at runtime

7️⃣

Hashing frozenset for caching

8️⃣

Using frozenset as function arguments

9️⃣

Making nested data structures immutable

🔟

Protecting global constants


Last updated