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)))
OutputThe 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))
Output3843673861956289951
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))
OutputThe 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
Similar Reads
ascii() in Python
In Python, we have ascii() function that returns a string containing a printable representation of an object. In this article, we will see about ascii() in Python. Python ascii() FunctionPython ascii() function returns a string containing a printable representation of an object and escapes the non-A
3 min read
bin() in Python
Python bin() function returns the binary string of a given integer. bin() function is used to convert integer to binary string. In this article, we will learn more about Python bin() function. Example In this example, we are using the bin() function to convert integer to binary string. C/C++ Code x
2 min read
bool() in Python
Python bool() function is used to return or convert a value to a Boolean value i.e., True or False, using the standard truth testing procedure. Example C/C++ Code x = bool(1) print(x) y = bool() print(y) OutputTrue False What is the bool() Method in Python?bool() is a built-in function of Python pro
4 min read
Python bytes() method
bytes() method in Python is used to create a sequence of bytes. In this article, we will check How bytes() methods works in Python. [GFGTABS] Python a = "geeks" # UTF-8 encoding is used b = bytes(a, 'utf-8') print(b) [/GFGTABS]Outputb'geeks' Table of Content bytes() Method SyntaxUs
3 min read
chr() Function in Python
chr() function returns a string representing a character whose Unicode code point is the integer specified. chr() Example: C/C++ Code num = 97 print("ASCII Value of 97 is: ", chr(num)) OutputASCII Value of 97 is: a Python chr() Function Syntaxchr(num) Parametersnum: an Unicode code integer
3 min read
Python dict() Function
A dictionary is a mutable data structure i.e. the data in the dictionary can be modified. A dictionary is an indexed data structure i.e. the contents of a dictionary can be accessed by using indexes, here in the dictionary, the key is used as an index. Here, the dict() function is used to create a n
4 min read
divmod() in Python and its application
In Python, divmod() method takes two numbers and returns a pair of numbers consisting of their quotient and remainder. In this article, we will see about divmod() function in Python and its application. Python divmod() Function Syntaxdivmod(x, y)x and y : x is numerator and y is denominatorx and y m
4 min read
Enumerate() in Python
enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list(). Let's look at a simple exa
3 min read
eval in Python
Python eval() function parse the expression argument and evaluate it as a Python expression and runs Python expression (code) within the program. Python eval() Function SyntaxSyntax: eval(expression, globals=None, locals=None) Parameters: expression: String is parsed and evaluated as a Python expres
6 min read
filter() in python
The filter() method filters the given sequence with the help of a function that tests each element in the sequence to be true or not. Let's see a simple example of filter() function in python: Example Usage of filter()[GFGTABS] Python # Function to check if a number is even def even(n): return n % 2
3 min read
float() in Python
Python float() function is used to return a floating-point number from a number or a string representation of a numeric value. Example: Here is a simple example of the Python float() function which takes an integer as the parameter and returns its float value. C/C++ Code # convert integer value to f
3 min read
Python String format() Method
The format() method is a powerful tool that allows developers to create formatted strings by embedding variables and values into placeholders within a template string. This method offers a flexible and versatile way to construct textual output for a wide range of applications. Python string format()
13 min read
Python - globals() function
In Python, the globals() function is a built-in function that returns a dictionary representing the current global symbol table. In this article, we will see the Python globals() function. globals() Function in PythonPython globals() function is a built-in function in Python that returns the diction
2 min read
Python hash() method
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 SyntaxSyntax : hash(obj) Parameters : obj : The object which we need
6 min read
hex() function in Python
,The hex() function is one of the built-in functions in Python3, which is used to convert an integer number into its corresponding hexadecimal form. Hexadecimal is a base-16 numbering system commonly used in computer science and programming. In this article, we will explore the hex() function and it
4 min read
id() function in Python
In Python, id() function is a built-in function that returns the unique identifier of an object. The identifier is an integer, which represents the memory address of the object. The id() function is commonly used to check if two variables or objects refer to the same memory location. Python id() Fun
3 min read
Python 3 - input() function
In Python, we use the input() function to take input from the user. Whatever you enter as input, the input function converts it into a string. If you enter an integer value still input() function converts it into a string. Python input() Function SyntaxSyntax: input(prompt) Parameter: Prompt: (optio
3 min read
Python int() Function
Python int() function returns an integer from a given object or converts a number in a given base to a decimal. Example: In this example, we passed a string as an argument to the int() function and printed it. C/C++ Code age = "21" print("age =", int(age)) Output: age = 21Python
4 min read
Python len() Function
len() function returns number of items in an object that can be characters, words, or elements in a sequence. Let’s start with a simple example to understand the len() functions with strings: [GFGTABS] Python s = "GeeksforGeeks" # Use len() to find the length of the string length = len(s)
2 min read
Python map() function
The map() function is used to apply a given function to every item of an iterable, such as a list or tuple, and returns a map object (which is an iterator). Let's start with a simple example of using map() to convert a list of strings into a list of integers. [GFGTABS] Python s = ['1', '
4 min read
Python - max() function
Python max() function returns the largest item in an iterable or the largest of two or more arguments. It has two forms. max() function with objectsmax() function with iterablePython max() function With ObjectsUnlike the max() function of C/C++, the max() function in Python can take any type of obje
4 min read
memoryview() in Python
Python memoryview() function returns the memory views objects. Before learning more about memoryview() function let's see why do we use this function. Why do we use memoryview() function? As Memory view is a safe way to expose the buffer protocol in Python and a memoryview behaves just like bytes in
4 min read
Python min() Function
Python min() function returns the smallest of the values or the smallest item in an iterable passed as its parameter. Example: Find Python min integer from the list [GFGTABS] Python numbers = [23,25,65,21,98] print(min(numbers)) [/GFGTABS]Output 21Python min() Function Syntaxmin(a, b, c, ..., key=fu
4 min read
Python next() method
Python's next() function returns the next item of an iterator. Example Let us see a few examples to see how the next() method in Python works. C/C++ Code l_iter = iter(l) print(next(l_iter)) Output1 Note: The .next() method was a method for iterating over a sequence in Python 2. It has been replaced
4 min read
Python oct() Function
Python oct() function takes an integer and returns the octal representation in a string format. In this article, we will see how we can convert an integer to an octal in Python. Python oct() Function SyntaxSyntax : oct(x) Parameters: x - Must be an integer number and can be in either binary, decimal
2 min read