Python hash() Built in Function

Python hash() is a built-in function that returns the hash value of an object if it has one. A hash value is an integer that represents the identity of an object and can be used to compare objects for equality or to store them in a dictionary or a set.

Here are some examples of how to use Python hash():

To get the hash value of different types of objects:

print(hash(181)) # returns 181
print(hash(181.23)) # returns 530343892119126197
print(hash("Python")) # returns 2230730083538390373 

To get the hash value of a user-defined class:

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


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


person1 = Person("John", 36)
person2 = Person("Mary", 28)

print(hash(person1)) # returns -9209083346939511628
print(hash(person2)) # returns -9209083346939511628

To use the hash value to check for object equality or membership:

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


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


    def __eq__(self, other):
        return (self.name, self.age) == (other.name, other.age)


person1 = Person("John", 36)
person2 = Person("Mary", 28)
person3 = Person("John", 36)


print(person1 == person3) # returns True
print(person2 == person3) # returns False


people = {person1, person2}
print(person3 in people)
# returns True

If you have any questions about this code, you can drop a line in comment.

Comments

Popular posts from this blog

Python chr() Built in Function

Stock Market Predictions with LSTM in Python

Collections In Python

Python Count Occurrence Of Elements

Python One Liner Functions