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

Python hash() method

Last Updated : 26 Jul, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.

Python
# 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.

Python
# 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.

Python
# 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.

Python
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.

Python
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


Python hash() method – FAQs

What does the hash() function do in Python?

The hash() function in Python takes an object (which must be hashable) and returns an integer hash value. This hash value is used for quick data retrieval in hash tables, such as dictionaries and sets. Hash values are used to compare dictionary keys during a dictionary lookup quickly.

How to hash immutable data types in Python?

Immutable data types like integers, floats, strings, and tuples can be hashed directly using the hash() function. Here are some examples:

# Hashing an integer
print(hash(42)) # Output: hash value of 42

# Hashing a float
print(hash(3.14)) # Output: hash value of 3.14

# Hashing a string
print(hash("hello")) # Output: hash value of "hello"

# Hashing a tuple
print(hash((1, 2, 3))) # Output: hash value of the tuple (1, 2, 3)

Can we hash mutable objects with the hash() method in Python?

No, mutable objects like lists, dictionaries, and sets cannot be hashed with the hash() function. Attempting to do so will result in a TypeError. This is because the hash value of an object must remain constant during its lifetime, and mutable objects can change, leading to inconsistent hash values.

# Trying to hash a list
try:
print(hash([1, 2, 3]))
except TypeError as e:
print(e) # Output: unhashable type: 'list'

What are hash collisions and how does Python handle them?

Hash collisions occur when two distinct objects produce the same hash value. Python handles hash collisions using a technique called “open addressing” or “chaining” (depending on the implementation). In open addressing, Python probes for the next available slot in the hash table, while in chaining, it stores colliding items in a linked list at the hash table index.

Python’s dictionary and set implementations use open addressing to resolve collisions, ensuring that even if multiple keys have the same hash value, they can be stored and retrieved efficiently.

How to use the hash() method for custom objects in Python?

To make a custom object hashable, you need to implement the __hash__() method and the __eq__() method in your class. The __hash__() method should return an integer hash value, and the __eq__() method should define equality comparison for the object.

Here’s an example:

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

def __eq__(self, other):
if isinstance(other, Person):
return self.name == other.name and self.age == other.age
return False

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

# Creating instances
person1 = Person("Alice", 30)
person2 = Person("Bob", 25)
person3 = Person("Alice", 30)

# Using the custom objects in a set
people = {person1, person2, person3}
print(len(people)) # Output: 2 (person1 and person3 are considered equal and have the same hash)

# Checking hashes
print(hash(person1)) # Output: hash value of person1
print(hash(person2)) # Output: hash value of person2
print(hash(person3)) # Output: same hash value as person1

In this example, the Person class has implemented __hash__() and __eq__(), making its instances hashable and usable in hash-based collections like sets and dictionaries



Previous Article
Next Article

Similar Reads

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
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
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
6 min read
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
5 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
Class Method vs Static Method vs Instance Method in Python
Three important types of methods in Python are class methods, static methods, and instance methods. Each serves a distinct purpose and contributes to the overall flexibility and functionality of object-oriented programming in Python. In this article, we will see the difference between class method, static method, and instance method with the help o
5 min read
Difference between Method Overloading and Method Overriding in Python
Method Overloading: Method Overloading is an example of Compile time polymorphism. In this, more than one method of the same class shares the same method name having different signatures. Method overloading is used to add more to the behavior of methods and there is no need of more than one class for method overloading.Note: Python does not support
3 min read
Class method vs Static method in Python
In this article, we will cover the basic difference between the class method vs Static method in Python and when to use the class method and static method in python. What is Class Method in Python? The @classmethod decorator is a built-in function decorator that is an expression that gets evaluated after your function is defined. The result of that
5 min read
Pandas DataFrame iterrows() Method | Pandas Method
Pandas DataFrame iterrows() iterates over a Pandas DataFrame rows in the form of (index, series) pair. This function iterates over the data frame column, it will return a tuple with the column name and content in the form of a series. Example: Python Code import pandas as pd df = pd.DataFrame({ 'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [25, 32, 3
2 min read
Pandas DataFrame interpolate() Method | Pandas Method
Python is a great language for data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier.  Python Pandas interpolate() method is used to fill NaN values in the DataFrame or Series using various interpolation techniques to fill the m
3 min read
Pandas DataFrame duplicated() Method | Pandas Method
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas duplicated() method identifies duplicated rows in a DataFrame. It returns a boolean series which is True only for unique rows. Ex
3 min read
What is the Proper Way to Call a Parent's Class Method Inside a Class Method?
In object-oriented programming, calling a parent class method inside a class method is a common practice, especially when you want to extend or modify the functionality of an inherited method. This process is known as method overriding. Here's how to properly call a parent class method inside a class method in Python. Basic Syntax Using super()The
3 min read
Real-Time Edge Detection using OpenCV in Python | Canny edge detection method
Edge detection is one of the fundamental image-processing tasks used in various Computer Vision tasks to identify the boundary or sharp changes in the pixel intensity. It plays a crucial role in object detection, image segmentation and feature extraction from the image. In Real-time edge detection, the image frame coming from a live webcam or video
5 min read
Python | os._exit() method
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os._exit() method in Python is used to exit the process with specified status without calling cleanup handlers, flushing stdio buff
2 min read
Python | os.WEXITSTATUS() method
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.WEXITSTATUS() method in Python is used to get the integer parameter used by a process in exit(2) system call if os.WIFEXITED(sta
3 min read
Python | os.abort() method
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.abort() method in Python is used to generate a SIGABRT signal to the current process. On Unix, this method produces a core dump
2 min read
Python | os.renames() method
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.renames() method is a recursive directory or file renaming function. It works like os.rename() method except creation of any int
2 min read
Python | os.lseek() method
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.lseek() method sets the current position of file descriptor fd to the given position pos which is modified by how. Syntax: os.ls
3 min read
Python calendar module : formatmonth() method
Calendar module allows to output calendars like program, and provides additional useful functions related to the calendar. Functions and classes defined in Calendar module use an idealized calendar, the current Gregorian calendar extended indefinitely in both directions. class calendar.TextCalendar(firstweekday=0) can be used to generate plain text
2 min read
Python | PyTorch sin() method
PyTorch is an open-source machine learning library developed by Facebook. It is used for deep neural network and natural language processing purposes. The function torch.sin() provides support for the sine function in PyTorch. It expects the input in radian form and the output is in the range [-1, 1]. The input type is tensor and if the input conta
2 min read
Python | Sympy Line.is_parallel() method
In Sympy, the function is_parallel() is used to check whether the two linear entities are parallel or not. Syntax: Line.is_parallel(l2) Parameters: l1: LinearEntity l2: LinearEntity Returns: True: if l1 and l2 are parallel, False: otherwise. Example #1: # import sympy and Point, Line from sympy import Point, Line p1, p2 = Point(0, 0), Point(1, 1) p
1 min read
Python PIL | GaussianBlur() method
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The ImageFilter module contains definitions for a pre-defined set of filters, which can be used with the Image.filter() method. PIL.ImageFilter.GaussianBlur() method create Gaussian blur filter. Syntax: PIL.ImageFilter.GaussianBlur(radius=5) Par
1 min read
Python range() Method
There are many iterables in Python like list, tuple etc. range() gives another way to initialize a sequence of numbers using some conditions.range() is commonly used in for looping hence, knowledge of same is key aspect when dealing with any kind of Python code. Syntax : range(start, stop, step)Parameters : start : Element from which sequence const
3 min read
Python String casefold() Method
Python String casefold() method is used to convert string to lowercase. It is similar to the Python lower() string method, but the case removes all the case distinctions present in a string. Python String casefold() Method Syntax Syntax: string.casefold() Parameters: The casefold() method doesn't take any parameters. Return value: Returns the case
1 min read
Python String isspace() Method
Python String isspace() method returns “True” if all characters in the string are whitespace characters, Otherwise, It returns “False”. This function is used to check if the argument contains all whitespace characters, such as: ‘ ‘ – Space‘\t’ – Horizontal tab‘\n’ – Newline‘\v’ – Vertical tab‘\f’ – Feed‘\r’ – Carriage returnPython String isspace()
2 min read
Python String isalpha() Method
Python String isalpha() method is used to check whether all characters in the String are an alphabet. Python String isalpha() Method SyntaxSyntax: string.isalpha() Parameters: isalpha() does not take any parameters Returns: True: If all characters in the string are alphabet.False: If the string contains 1 or more non-alphabets.Errors and Exceptions
4 min read
Practice Tags :