the hash() function
✅ What is hash()?
hash() returns a hash value (an integer) for an object.
👉 Hash values are used internally in:
Dictionaries (dict)
Sets (set)
Only immutable objects are hashable.
1️⃣ Hash of an Integer
x = 10
print(hash(x))
Output (example):
10
✔ For integers, the hash value is usually the integer itself.
2️⃣ Hash of a String
name = "Vijay"
print(hash(name))
Output (example – will differ each run):
-8392749283749283
⚠ String hash values may change between Python runs (security feature).
3️⃣ Hash of a Float
num = 10.5
print(hash(num))
Output:
1152921504606846986
✔ Floats are also hashable.
4️⃣ Equal Objects Have Equal Hash
print(hash(5))
print(hash(5))
Output:
5
5
Rule:
If a == b, then hash(a) == hash(b)
Example:
print(hash(10))
print(hash(10.0))
Output:
10
10
Why?
Because:
10 == 10.0 # True
5️⃣ Hash of a Tuple (Immutable)
t = (1, 2, 3)
print(hash(t))
✔ Works because tuple is immutable.
6️⃣ Hash of a List (Error)
lst = [1, 2, 3]
print(hash(lst))
Output:
TypeError: unhashable type: 'list'
❌ Lists are mutable → Not hashable.
7️⃣ Using hash() in Dictionary (Internal
Usage)
student = {
"name": "Vijay",
"age": 25
}
print(student["name"])
Behind the scenes:
hash("name") → determines storage index
Dictionaries use hash values to store and retrieve keys efficiently.
8️⃣ Hash of a Custom Object
class Person:
pass
p = Person()
print(hash(p))
✔ Default hash is based on object identity (memory address).
Each object gives different hash:
p1 = Person()
p2 = Person()
print(hash(p1))
print(hash(p2))
Different output values.
🔎 Quick Summary
Type Hashable? Why
int ✅ Yes Immutable
float ✅ Yes Immutable
str ✅ Yes Immutable
tuple ✅ Yes Immutable
list ❌ No Mutable
dict ❌ No Mutable
set ❌ No Mutable
🧠 Simple Rule to Remember
👉 Immutable objects → Usually hashable
👉 Mutable objects → Not hashable
*Note:
All objects that compare equal must have the same hash value, even if they are of different
types.
If the type of obj does not define equality comparison, hash(obj) normally returns id(obj)