The Wayback Machine - https://web.archive.org/web/20240709152108/https://www.geeksforgeeks.org/python-hash-method/
Open In App

Python hash() method

Last Updated : 30 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Python hash() function is a built-in function and returns the hash value of an object if it has one. The hash value is an integer that is used to quickly compare dictionary keys while looking at a dictionary.

Python hash() function Syntax

Syntax : hash(obj)

Parameters :  obj : The object which we need to convert into hash.

Returns : Returns the hashed value if possible. 

Properties of hash() function

  • Objects hashed using hash() are irreversible, leading to loss of information.
  • hash() returns hashed value only for immutable objects, hence can be used as an indicator to check for mutable/immutable objects.
  • We can encode data for security in Python by using hash() function.

Python hash() Function Examples

Example 1: Demonstrating working of hash()

In this example, we are using hash() function to print the integer, string, and float hash value using hash() in Python.

Python3




# initializing objects
int_val = 4
str_val = 'GeeksforGeeks'
flt_val = 24.56
 
# Printing the hash values.
# Notice Integer value doesn't change
# You'll have answer later in article.
print("The integer hash value is : " + str(hash(int_val)))
print("The string hash value is : " + str(hash(str_val)))
print("The float hash value is : " + str(hash(flt_val)))


Output

The integer hash value is : 4
The string hash value is : 4349415460800802357
The float hash value is : 1291272085159665688


Example 2: Demonstrating property of hash() 

This Python code demonstrates how the hash() function behaves with immutable and mutable objects. It first initializes a tuple and a list with the same elements. The code successfully prints the hash value of the tuple. However, when it attempts to print the hash value of the list, which is mutable, it raises a TypeError because mutable objects like lists can’t be hashed directly.

Python3




# initializing objects
# tuple are immutable
tuple_val = (1, 2, 3, 4, 5)
 
# list are mutable
list_val = [1, 2, 3, 4, 5]
 
# Printing the hash values.
# Notice exception when trying
# to convert mutable object
print("The tuple hash value is : " + str(hash(tuple_val)))
print("The list hash value is : " + str(hash(list_val)))


Output: 

The tuple hash value is : 8315274433719620810

Exceptions : 

Traceback (most recent call last):
File "/home/eb7e39084e3d151114ce5ed3e43babb8.py", line 15, in
print ("The list hash value is : " + str(hash(list_val)))
TypeError: unhashable type: 'list'

Example 3: hash() for Immutable Tuple Object

This Python code initializes a tuple named var containing the characters ‘G’, ‘E’, ‘E’, and ‘K’. The hash() function is used to generate a hash value for the tuple var. In this case, the code prints the hash value of the tuple, which is a unique integer that represents the tuple based on its content and structure.

Python3




# hash() for immutable tuple object
var = ('G','E','E','K')
 
print(hash(var))


Output

3843673861956289951


Example 4: hash() on the Mutable Object

hash() method used by one immutable object, if we use this on a mutable object like list, set, dictionaries then it will generate an error.

Python3




l = [1, 2, 3, 4]
print(hash(l))


Output

TypeError: unhashable type: 'list'

Example 5: hash() on a Custom Object

Here we will override the __hash()__ methods to call the hash(), and __eq__() method will check the equality of the two custom objects.

Python3




class Emp:
    def __init__(self, emp_name, id):
        self.emp_name = emp_name
        self.id = id
 
    def __eq__(self, other):
       
        # Equality Comparison between two objects
        return self.emp_name == other.emp_name and self.id == other.id
 
    def __hash__(self):
       
        # hash(custom_object)
        return hash((self.emp_name, self.id))
 
emp = Emp('Ragav', 12)
print("The hash is: %d" % hash(emp))
 
# We'll check if two objects with the same
# attribute values have the same hash
emp_copy = Emp('Ragav', 12)
print("The hash is: %d" % hash(emp_copy))


Output

The hash is: 7627717261227283506
The hash is: 7627717261227283506




Previous Article
Next Article

Similar Reads

MD5 hash in Python
Cryptographic hashes are used in day-day life like in digital signatures, message authentication codes, manipulation detection, fingerprints, checksums (message integrity check), hash tables, password storage and much more. They are also used in sending messages over network for security or storing messages in databases. There are many hash functio
2 min read
Python 3.6 Dictionary Implementation using Hash Tables
Dictionary in Python is a collection of data values, used to store data values like a map, which, unlike other Data Types that hold only a single value as an element, Dictionary holds key:value pair. Key-value is provided in the dictionary to make it more optimized. Each key-value pair in a Dictionary is separated by a colon :, whereas each key is
3 min read
Whirlpool Hash Function in Python
Hash Function is a function which has a huge role in making a System Secure as it converts normal data given to it as an irregular value of fixed length. We can imagine it to be a Shaker in our homes. When we put data into this function it outputs an irregular value. The Irregular value it outputs is known as “Hash Value”.Hash Values are simply num
2 min read
Full domain Hashing with variable Hash size in Python
A cryptographic hash function is a special class of hash function that has certain properties which make it suitable for use in cryptography. It is a mathematical algorithm that maps data of arbitrary size to a bit string of a fixed size (a hash function) which is designed to also be a one-way function, that is, a function which is infeasible to in
5 min read
Hash Map in Python
Hash maps are indexed data structures. A hash map makes use of a hash function to compute an index with a key into an array of buckets or slots. Its value is mapped to the bucket with the corresponding index. The key is unique and immutable. Think of a hash map as a cabinet having drawers with labels for the things stored in them. For example, stor
4 min read
How To Hash Passwords In Python
In this article, we are going to know how to hash passwords in python. A strong password provides safety. Plain text passwords are extremely insecure, so we need to strengthen the passwords by hashing the password. Hashing passwords is a cheap and secure method that keeps the passwords safe from malicious activity. Password hashing generates a uniq
4 min read
Bidirectional Hash table or Two way dictionary in Python
We know about Python dictionaries in a data structure in Python which holds data in the form of key: value pairs. In this article, we will discuss the Bidirectional Hash table or Two-way dictionary in Python. We can say a two-way dictionary can be represented as key ⇐⇒ value. One example of two-way dictionaries is: Example: dict={ 1 : 'Apple' , 2 :
3 min read
Generating hash id's using uuid3() and uuid5() in Python
Python's UUID class defines four functions and each generates different version of UUIDs. Let's see how to generate UUID based on MD5 and SHA-1 hash using uuid3() and uuid5() .Cryptographic hashes can be used to generate different ID's taking NAMESPACE identifier and a string as input. The functions that support cryptographic hash generation are :
2 min read
Python Program to find hash of file
In this tutorial, we will learn how to create a Python program to compute the hash of a file using various hashing algorithms. The program uses the hashlib module and handles large files efficiently by reading them in chunks. It also includes error handling for invalid file paths and hashing algorithms Setting Up the Environment to find hash of fil
3 min read
RIPEMD Hash Function
Hash Function is a function that has a huge role in making a System Secure as it converts normal data given to it as an irregular value of fixed length. We can imagine it to be a Shaker in our homes. When we put data into this function it outputs an irregular value. The Irregular value it outputs is known as "Hash Value". Hash Values are simply num
3 min read
Practice Tags :
three90RightbarBannerImg