0% found this document useful (0 votes)
4 views3 pages

Python Hash

The Python hash() function generates a hash value for immutable objects, which is useful for quickly comparing dictionary keys. It cannot hash mutable objects like lists, resulting in a TypeError, and can be used to encode data for security. The document includes examples demonstrating the function's behavior with different data types and custom objects.

Uploaded by

Vidhi Handa
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views3 pages

Python Hash

The Python hash() function generates a hash value for immutable objects, which is useful for quickly comparing dictionary keys. It cannot hash mutable objects like lists, resulting in a TypeError, and can be used to encode data for security. The document includes examples demonstrating the function's behavior with different data types and custom objects.

Uploaded by

Vidhi Handa
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

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 = 'Agasthya'
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/[Link]", 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 = ('A','G','A','S','T','H','Y','A')

print(hash(var))

Output
-1813161384

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
[Link] = id

def __eq__(self, other):

# Equality Comparison between two objects


return self.emp_name == other.emp_name and [Link] == [Link]

def __hash__(self):

# hash(custom_object)
return hash((self.emp_name, [Link]))

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

You might also like