Hash Function in Python
Definition, Working, Properties, and
Examples
Definition
• A hash function is a function that converts
input data (key) into a fixed-size numerical
value called a hash code.
• It is mainly used in data structures like hash
tables, dictionaries, and sets for fast data
retrieval.
Working Principle
• 1. The key (like a name or number) is given as
input.
• 2. The hash function computes a numeric hash
value.
• 3. That value is used as an index in a hash
table to store or find the data.
• Example:
• Key → "apple"
Hash Function in Python
• Python provides a built-in function called
hash().
• Example:
• print(hash("hello"))
• print(hash(123))
• Used internally by:
• - dict (dictionary)
• - set
Properties of a Good Hash
Function
• • Uniform Distribution – Distributes keys
evenly
• • Deterministic – Same input gives same
output
• • Fast – Quick to compute
• • Low Collisions – Different keys produce
different hash values
• • Equality Consistency – If a == b → hash(a) ==
hash(b)
Example of a Simple Hash Function
• def simple_hash(key):
• h=0
• for ch in key:
• h += ord(ch)
• return h % 10 # table size = 10
• print(simple_hash("apple"))
• print(simple_hash("banana"))
Applications of Hash Functions
• • Hash Tables / Dictionaries
• • Password Storage (Encryption)
• • Data Integrity (Checksums)
• • Cryptography (SHA, MD5, etc.)