0
0
PythonHow-ToBeginner · 3 min read

How to Use Hash Function in Python: Simple Guide

In Python, you use the hash() function to get a unique integer value for immutable objects like strings, numbers, or tuples. This integer can help you quickly compare or store objects in data structures like sets or dictionaries.
📐

Syntax

The hash() function takes one argument, which must be an immutable object, and returns an integer representing its hash value.

  • hash(object): Returns the hash value of the given object.
  • The object must be immutable (e.g., strings, numbers, tuples).
  • Mutable objects like lists or dictionaries cannot be hashed and will raise an error.
python
hash(object)
💻

Example

This example shows how to use hash() on different immutable objects like a string, a number, and a tuple. It prints their hash values.

python
print(hash('hello'))
print(hash(123))
print(hash((1, 2, 3)))
⚠️

Common Pitfalls

Common mistakes include trying to hash mutable objects like lists or dictionaries, which causes a TypeError. Also, hash values can differ between Python runs for security reasons, so don't rely on them being the same every time.

python
try:
    print(hash([1, 2, 3]))  # This will cause an error
except TypeError as e:
    print(f'Error: {e}')

# Correct way: use a tuple instead
print(hash((1, 2, 3)))
📊

Quick Reference

  • Use hash() for immutable objects only.
  • Returns an integer that represents the object.
  • Useful for dictionary keys, sets, and quick comparisons.
  • Hash values may change between program runs.

Key Takeaways

Use hash() to get an integer hash value of immutable objects in Python.
Mutable objects like lists cannot be hashed and will raise a TypeError.
Hash values are useful for fast lookups in sets and dictionaries.
Hash values can change between Python runs, so don't store them permanently.
Always use immutable types like strings, numbers, or tuples with hash().