The syntax for the "hash()" function is as follows:
|
hash(object)
|
where "object" is the object that we want to compute the hash value for. The function returns an integer value that represents the hash value for the object.
Example 1: Using "hash()" with Strings
|
string1 = "Hello World"
string2 = "Hello World"
string3 = "Python"
print(hash(string1))
print(hash(string2))
print(hash(string3))
|
In this example, we have defined three strings, "string1", "string2", and "string3". We then print out the hash value of each string using the "hash()" function. Since the strings "string1" and "string2" have the same contents, their hash values will be the same. However, the hash value of "string3" will be different since its contents are different.
Output:
|
-1787971910664652609
-1787971910664652609
-4833947030733741538
|
Example 2: Using "hash()" with Tuples
|
tuple1 = (1, 2, 3)
tuple2 = (1, 2, 3)
tuple3 = (4, 5, 6)
print(hash(tuple1))
print(hash(tuple2))
print(hash(tuple3))
|
In this example, we have defined three tuples, "tuple1", "tuple2", and "tuple3". We then print out the hash value of each tuple using the "hash()" function. Since the tuples "tuple1" and "tuple2" have the same contents, their hash values will be the same. However, the hash value of "tuple3" will be different since its contents are different.
Output:
|
2528502973977326415
2528502973977326415
3713083796996140657
|
Example 3: Using "hash()" with Custom Objects
|
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person1 = Person("John", 30)
person2 = Person("John", 30)
person3 = Person("Mary", 25)
print(hash(person1))
print(hash(person2))
print(hash(person3))
|
In this example, we have defined a custom class "Person" with two attributes, "name" and "age". We then create three instances of the class, "person1", "person2", and "person3". We then print out the hash value of each object using the "hash()" function. Since "person1" and "person2" have the same contents, their hash values will be the same. However, the hash value of "person3" will be different since its contents are different.
Output:
|
-9223372036577670770
-9223372036577670770
-9223372036577670716
|
In conclusion, the "hash()" function is a powerful tool in Python that is used to generate unique hash values for objects. The hash values generated by this function are used in various data structures and algorithms, such as hash tables and dictionaries. However, it is important to note that the hash values generated by the "hash()" function.