Yandex

Python hash() Function – Generate Hash Values of Objects



Python hash() Function

The hash() function in Python returns the hash value of an object. It is commonly used in hashing data structures like sets and dictionaries.

Syntax

hash(object)

Parameters:

  • object – The input object must be immutable (like int, float, str, tuple with only hashable items).

Returns:

  • An integer hash value that represents the object.

Example 1: Hashing Numbers

print(hash(42))
print(hash(-42))
print(hash(3.14))
(Output will be integer values like 42 or -42 or some number)

Example 2: Hashing Strings

print(hash("hello"))
print(hash("HELLO"))
(Will return integer hash values for each string)

Example 3: Using hash() with Tuples

print(hash((1, 2, 3)))
(Returns an integer hash)

Use Case: Why use hash()?

  • To store objects in sets or as dictionary keys.
  • To compare objects efficiently by their hash.
  • To build data structures like hash tables.

Important Notes

  • Only immutable objects can be hashed.
  • Mutable types like list or dict will raise a TypeError.
  • Hash values may differ across Python sessions (especially for strings).

Example 4: Unhashable Object (Throws Error)

print(hash([1, 2, 3]))  # List is mutable
TypeError: unhashable type: 'list'

Custom Hash in Classes


class MyClass:
    def __init__(self, value):
        self.value = value

    def __hash__(self):
        return hash(self.value)

obj = MyClass(100)
print(hash(obj))
(Depends on the value passed)

Interview Tip

Interviewers often ask about hash-based data structures. Understanding hash() is key to explaining how dict and set work in Python.

Summary

  • hash() returns a unique integer based on the object's content.
  • Used in sets, dicts, and custom objects.
  • Only immutable objects can be hashed.

Practice Problem

Write a program to find and print the hash values of a string, a tuple, and an integer input from the user.


text = input("Enter a string: ")
number = int(input("Enter an integer: "))
tpl = (text, number)

print("Hash of string:", hash(text))
print("Hash of integer:", hash(number))
print("Hash of tuple:", hash(tpl))


Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M