Sobes.tech
Middle

What is the connection between hash functions and mutable/immutable objects?

sobes.tech AI

Answer from AI

Objects in Python are divided into mutable and immutable. The connection with hash functions is that only immutable objects are hashable and, therefore, can be used as dictionary keys or set elements.

  • Immutable objects: string (str), tuple (tuple), number (int, float, bool), NoneType, etc. Their value cannot be changed after creation. Python computes the hash value for such objects once.
  • Mutable objects: list (list), dictionary (dict), set (set), etc. Their value can be changed after creation. If mutable objects were hashable, their hash value could change after being added to a dictionary or set, which would break the functionality of hash-based data structures.

The connection manifests when using dictionaries and sets:

  • Dictionaries: Use hash tables for quick access to values by key. Dictionary keys must be hashable.
  • Sets: Also use hash tables to store unique elements. Elements of a set must be hashable.
# This works because a tuple is an immutable object
my_dict = {(1, 2): 'hello'}
my_set = {(1, 2)}
# This will raise a TypeError because a list is a mutable object
# my_dict = {[1, 2]: 'hello'}
# my_set = {[1, 2]}

# TypeError: unhashable type: 'list'