hash(): hash value of an object

A hash is an fixed sized integer that identifies a particular value.
hash(object) : Returns the hash value of the input object ( if available )
Hashable and Immutable
hash() value is available for immutable objects ( what is immutable and mutable object ?), but all Hashable are not immutable.

print(hash(300))        # 300 
print(hash(300.56))     #1291272085159674156
print(hash('plus2net')) #-4778224534751702784
hash value of tuple
my_tuple=('Alex','Ronald','John')
print(hash(my_tuple))      # 7654376616106661247
hash value of list
my_list=['Alex','Ronald','John']
print(hash(my_list)) # Error
Above code will generate error
 TypeError: unhashable type: 'list'
hash() value of user defined object
class student_kit():
    college_name='ABC College'  #class attributes

     #instance attributes
    def __init__(self,name,section):
        self.name= name
        self.section=section
        self.height=5  #instance attribute

Alex=student_kit('Alex','A')  # object declaration

print(hash(Alex))  # -9223371866271725652

Key Points About hash() Function

  • Immutability: Only immutable types can be hashed because their hash value must remain constant throughout their lifetime.
  • Uniqueness: While the hash function aims to return a unique hash value for each unique value, it is possible for two different values to have the same hash value, a situation known as a hash collision.
  • Use in Data Structures: Hash values are integral to the efficiency of Python data structures like sets and dictionaries, allowing for quick data access.

Limitations of hash() Function

While the hash() function is powerful, it has limitations, particularly the potential for hash collisions. Additionally, the specific hash values for objects are not guaranteed to be the same across different versions of Python or even different executions of the same program. Therefore, hash values should not be used for cryptographic purposes or persisted for long-term storage.

In summary, the hash() function provides a way to obtain a hash value for immutable objects, playing a crucial role in the performance of data structures like dictionaries and sets in Python.
All Built in Functions in Python
id() Mutable & Immutable object Bitwise operators using hash() int() float()


Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



    Post your comments , suggestion , error , requirements etc here





    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer