Python program to find hash from a given tuple

The hash() function in Python computes a hash value for hashable objects like tuples. Hash values are integers used internally by Python for dictionary keys and set membership tests. Tuples are hashable because they are immutable, unlike lists which cannot be hashed due to their mutable nature.

Syntax

hash(object)

Where object must be a hashable type (int, float, string, tuple, etc.).

Example

Let's find the hash value of a tuple containing integers ?

def solve(t):
    return hash(t)

t = (2, 4, 5, 6, 7, 8)
result = solve(t)
print(f"Hash value of {t}: {result}")
Hash value of (2, 4, 5, 6, 7, 8): -6569923111468529526

Hashing Different Tuple Types

The hash() function works with tuples containing various data types ?

# Integer tuple
int_tuple = (1, 2, 3)
print(f"Integer tuple hash: {hash(int_tuple)}")

# String tuple
str_tuple = ("apple", "banana", "cherry")
print(f"String tuple hash: {hash(str_tuple)}")

# Mixed tuple
mixed_tuple = (1, "hello", 3.14)
print(f"Mixed tuple hash: {hash(mixed_tuple)}")

# Empty tuple
empty_tuple = ()
print(f"Empty tuple hash: {hash(empty_tuple)}")
Integer tuple hash: 2528502973977326415
String tuple hash: -4282852307117485614
Mixed tuple hash: 5434205749029823783
Empty tuple hash: 3527539

Key Points

  • Hash values are consistent within a single Python session but may vary between sessions

  • Only immutable objects (tuples, strings, numbers) are hashable

  • Tuples containing mutable objects (like lists) cannot be hashed

  • Hash values are used internally by dictionaries and sets for fast lookups

Error Example

Attempting to hash a tuple containing mutable objects raises an error ?

try:
    # This will raise TypeError
    unhashable_tuple = ([1, 2], [3, 4])
    print(hash(unhashable_tuple))
except TypeError as e:
    print(f"Error: {e}")
Error: unhashable type: 'list'

Conclusion

The hash() function generates integer hash values for immutable objects like tuples. This is essential for Python's internal dictionary and set operations, enabling fast data retrieval and membership testing.

Updated on: 2026-03-26T15:28:34+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements