[python] hashable vs unhashable

 hashable vs unhashable

Syntax

in Python, there are hashable objects and unhashable objects. 

Hashable objects

  • they have a hash values that doesn't change across the object's lifetime.
  • Immutable built-ins are hashable.
    • string, integers, floats, tuples of hashable elements.

Unhashable objects

  • they are mutable.
  • List and Dictionary are unhashable.

Example

key_tuple = ("a", 1)
some_dict = {key_tuple: "Hashable tuple"}

This would not cause any errors, since key_tuple here is hashable.

my_list = [1, 2]
some_dict = {my_list: "Unhashable"}  # Raises TypeError

This would raise an error, since key_tuple here is unhashable.


Comments