Python hash()

Python hash() is a built-in function that generates a unique integer value for an object. This "hash value" helps quickly identify and compare objects in data structures like dictionaries and sets. While immutable types (numbers, strings, tuples) work with hash(), mutable objects (lists, dictionaries) cannot be hashed and will raise an error.
Table of Contents

Understanding Python hash() Function

Python hash() function returns an integer representing an object’s hash value. This function quickly compares dictionary keys, as dictionaries rely on hash values for efficient lookup. Only immutable objects, like strings, numbers, and tuples, can have hash values in Python. If you attempt to call hash() on a mutable object like a list or dictionary, you’ll get a TypeError. Python hash() is a core functionality that works with objects and collections.

Syntax of Python hash()

hash(object)

Explanation

  • hash(): Built-in Python function.
  • object: Object you want to get the hash value of.

Example of Python hash()

string_to_hash = "Hello"
hashed_string = hash(string_to_hash)
print(hashed_string)

Explanation

  • string_to_hash = "Hello": Assigns the string “Hello” to the variable.
  • hashed_string = hash(string_to_hash): Calls hash() function on string_to_hash.
  • print(hashed_string): Prints the returned integer hash value.

Output

-8338684742150164606


hash() Parameters

The hash() method takes a single parameter: the object you want to hash. This object must be immutable. If you supply a mutable object, such as a list, Python raises an error. Internally, hash() interacts with the object’s __hash__() method. Therefore, the behavior of hash() depends on how that underlying method is defined or if it’s even defined at all.

Syntax

hash(object_to_hash)

Example

integer_val = 123
hashed_integer = hash(integer_val)
print(hashed_integer)

Explanation

  • integer_val = 123: An integer value is assigned.
  • hashed_integer = hash(integer_val): hash() function is called with the integer.
  • print(hashed_integer): The hash value of integer is printed.

Output

123


hash() Return Value

The hash() function provides an integer. This integer represents the object’s hash value. Identical objects have the same hash value. Be aware that two different objects may result in the same hash value, which is called a hash collision. The return value can be positive or negative.

Syntax

returned_hash_value = hash(any_object)

Example

float_number = 3.14159
hashed_float = hash(float_number)
print(hashed_float)

Explanation

  • float_number = 3.14159: Assigns a floating-point number to a variable.
  • hashed_float = hash(float_number): Get hash value for float_number.
  • print(hashed_float): Prints the hash value.

Output

461168601842738689


Python hash() for Immutable Tuple Object

Tuples, being immutable, are excellent candidates to use with the Python hash() function. You can reliably generate a hash value for a tuple, and this value won’t change during the tuple’s lifetime. You can use a tuple as a key within a dictionary without any issues. This gives you the ability to key dictionaries on more complex compound values.

Syntax

hash_value = hash(my_tuple)

Explanation

  • hash_value: Variable that stores integer value that hash() returns.
  • my_tuple: Immutable tuple object.

Example

tuple_data = (1, 2, 3)
hashed_tuple = hash(tuple_data)
print(hashed_tuple)

Explanation

  • tuple_data = (1, 2, 3): Creates a tuple.
  • hashed_tuple = hash(tuple_data): Gets the hash of tuple_data.
  • print(hashed_tuple): Displays the hash value.

Output

2528502973977326415


Python hash() on the Mutable Object

You cannot use Python hash() directly on mutable objects. If you try, Python will raise a TypeError. Mutable objects, like lists and dictionaries, do not have stable hash values because their contents can change. For example, trying to hash a list breaks fundamental assumptions that dictionaries and sets make about consistent hash values.

Syntax

# This will cause an error
# hash(mutable_object)

Explanation

  • hash() : Calling function on a mutable_object.
  • mutable_object: Represents any mutable object like a list or a dictionary.

Example

# Attempting to hash a list will raise a TypeError
my_list = [1, 2, 3]
try:
    hashed_list = hash(my_list)
    print(hashed_list)
except TypeError as e:
    print(e)

Explanation

  • my_list = [1, 2, 3]: Creates a mutable list.
  • try...except: Handles the expected TypeError.
  • hashed_list = hash(my_list): Attempts to get the hash, which will trigger the error.
  • print(e): Prints Error.

Output

unhashable type: ‘list’


Python hash() on a Custom Object (eq(), hash())

When you create your custom classes, you can define how Python hash() behaves on instances of your class. You need to implement both the __eq__() and __hash__() special methods to do this. The __eq__() method defines how equality is checked between objects. The __hash__() method should return an integer that represents the hash value, ensuring objects that compare as equal have the same hash value.

Syntax

class MyClass:
    def __eq__(self, other):
        # Equality logic here
        pass

    def __hash__(self):
        # Return hash value
        pass

Explanation

  • class MyClass:: Defines start of the custom class.
  • def __eq__(self, other):: Defines how equality comparisons.
  • def __hash__(self)::Defines how the object generates a hash value.

Example

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __eq__(self, other):
        return self.name == other.name and self.age == other.age

    def __hash__(self):
        return hash((self.name, self.age))

person1 = Person("Alice", 30)
person2 = Person("Alice", 30)

print(hash(person1))
print(hash(person2))

Explanation

  • class Person:: Defines a class called Person.
  • def __init__(self, name, age):: Constructor to initialize object.
  • self.name = name and self.age = age: Assigns provided values.
  • def __eq__(self, other):: Defines equality.
  • return self.name == other.name and self.age == other.age: Checks if name and age are same.
  • def __hash__(self):: Defines the hashing behavior.
  • return hash((self.name, self.age)): Returns a hash value based on a tuple.
  • person1 = Person("Alice", 30) and person2 = Person("Alice", 30): Creates two Person instances.
  • print(hash(person1)) and print(hash(person2)): Prints hash values of the objects.

Output

-3789977732754734096
-3789977732754734096


Python hash() for Custom Objects by Overriding hash()

When defining custom classes, controlling the hash value can become important. While Python provides default hashing for objects, it might not always be suitable, particularly if you need specific attributes to determine equality and hashing. By overriding only the __hash__() method, you establish how instances of your custom class should be treated when inserted into hashed collections like dictionaries or sets.

Syntax

class CustomClass:
    def __hash__(self):
      #Return hash value here
      pass

Explanation

  • class CustomClass: Declares beginning of the custom class definition.
  • def __hash__(self):: Defines custom behavior for the hash() function when applied to instances of CustomClass.

Example

class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __hash__(self):
        return hash((self.x, self.y))
point1 = Point(1,5)
print(hash(point1))

Explanation

  • class Point: Defines the Point class.
  • def __init__(self, x, y): Initializes x and y coordinates.
  • def __hash__(self):: Specifies how to compute hash.
  • return hash((self.x, self.y)): Hash value is based on coordinates x and y.
  • point1 = Point(1,5): Instance of Point class.
  • print(hash(point1)): Displays hash value of the instance.

Output

3713081631934410656


Conclusion

The Python hash() is an important function. You learned that you can calculate the hash value for immutable data type. You also get familiar with mutable objects; Python will show TypeError. You get to know you can define the hash value calculation for custom classes by using __eq__() and __hash__() dunder methods.


Also Read

Python hex()

Python input()


Python Reference

Python hash()