python hashable types

If you have ever used sets or dictionaries in Python, then you have already used hashable types. Hashable objects play a big role in how Python handles data quickly and efficiently.

In this guide, you will learn what it means for an object to be hashable, why it matters, and which types in Python are hashable or not.

Whether you are a complete beginner or you are looking for a complete tutorial on python hashable types then this post is for you.

What Is “Hashable” in Python?

Before getting straight into hashable concept in python, let us first discuss what does hash mean. a hash in Python is a number that represents an object.

Python uses this number to quickly find or compare things especially when working with dictionaries and sets.

You can think of a hash like a shortcut label. Instead of looking at the entire object, Python just looks at the hash number to know where it is or if it is the same as another object.

For example:

print(hash("apple"))  # This gives a number like 734839457239 (varies)

This number is the hash of the word "apple". Python uses it behind the scenes to make searching and storing data faster. In short “A hash is a unique number used to identify an object in Python quickly”.

Now let’s understand the concept of hashable in python.

An object is hashable if it has a hash value that doesn’t change during its lifetime. This hash value is used to quickly compare dictionary keys and set members.

You can check the hash of an object using the built-in hash() function:

print(hash("hello"))  #  Works: string is hashable
print(hash(42))       #  Works: integer is hashable

But if you try to hash a list or dictionary, Python will raise an error:

print(hash([1, 2, 3]))  # TypeError: unhashable type: 'list'

Some Rules In Python

Sets Items Must Be Hashable

In Python, sets are collections of unique and unordered elements. But all items in a set must be hashable. That’s how Python checks for uniqueness and allows fast lookups.

my_set = {1, "apple", (2, 3)}  # All items are hashable

Try adding a list or dictionary to a set, and you will get an error:

my_set = {1, [2, 3]}  #  TypeError: unhashable type: 'list'

Dictionary Keys Must Be Hashable

Just like set items, dictionary keys must also be hashable. Python uses hash values to store and retrieve data in dictionaries quickly.

my_dict = { "name": "Alice", 42: "number" }  # Keys are hashabl

If you try using a mutable type like a list as a key, you will see:

my_dict = {[1, 2]: "oops"}  # TypeError

Hashability Makes Dictionaries and Sets Fast

Hashable objects allow Python to use a hash table under the hood. This structure lets you to check if an item exists in constant time i.e., O(1). That’s why dictionaries and sets are so efficient.

So if your object is hashable, it can be:

  • A dictionary key.
  • A set element.
  • Part of any algorithm that relies on fast lookups.

Every Hashable Object Has a Semi-Unique Hash Value

A hash value is a number which is generated using the object’s content.

For example:

print(hash("cat"))   # → e.g., 124587673 (your result may vary)
print(hash("dog"))   # → e.g., 354632118

Each hashable object has a hash that remains stable unless the object changes (which it should not if it is truly hashable).

Hashable Objects Are Often Immutable

Most hashable objects in Python are immutable. This means their content cannot change after creation.

Common Immutable (Hashable) Types:

  • int
  • float
  • str
  • tuple (if it contains only hashable elements)
  • frozenset

Common Mutable (Unhashable) Types:

  • list
  • dict
  • set

So, while (1, 2, 3) is hashable, ([1, 2], 3) is not, because it contains a list.

Hashability Is Linked to Equality

In Python, two objects that are equal (via ==) must also have the same hash. This is important for dictionary behavior.

a = (1, 2)
b = (1, 2)
print(a == b)          # True
print(hash(a) == hash(b))  # True

When creating custom classes, you must define both __eq__() and __hash__() to maintain this consistency.

An Object’s Hash Value Should Never Change

Always keep in mind that once an object is used as a dictionary key or a set item, its hash value must not change.

If you somehow change the contents of a hashable object (like a custom class), it can break your code.

That’s why hashable objects should be immutable by design.

A Frozenset Is a Hashable Set

Python’s set is mutable and unhashable. But frozenset is immutable and hashable. A frozenset is like a regular set in Python, but it cannot be changed after it is created. That’s why it is called “frozen.”

Because it doesn’t change, a frozenset is hashable, which means that you can use it as a key in a dictionary or put it inside another set.

fs = frozenset([1, 2, 3])
print(hash(fs))  #  Works!

You can use frozenset as a dictionary key or a set element.

Sets and Dictionaries Require Hashable Objects

To wrap this up: both sets and dictionaries rely on hashable types for fast lookups and data organization. Python raises an error when you try to use an unhashable type in either.

Hashable Types in Python

Here’s a quick reference:

HashableNot Hashable
intlist
floatdict
strset
boolbytearray
tuple*user-defined (mutable)
frozenset

Only if all elements inside the tuple are also hashable.

Python Hashable Objects: Learning the Key Concepts

  • Hashable = Has a stable __hash__() and __eq__() method.
  • Most built-in immutable types are hashable.
  • Hashable types are necessary for keys and set items.
  • Avoid using mutable objects as dictionary keys.

Exploring Python’s Hash Functions

In Python, hashable functions are the built-in tools that helps you to check if an object is hashable and let you use it in sets or as dictionary keys.

try:
    print(hash(my_object))
except TypeError:
    print("Object is not hashable")

Custom classes can also define using __hash__():

class Animal:
    def __init__(self, name):
        self.name = name

    def __hash__(self):
        return hash(self.name)

    def __eq__(self, other):
        return self.name == other.name

hashlib Module – For Secure Hashing

You can use this module for cryptographic hashes (used in passwords, file integrity, etc.). hashlib is a built-in Python module that lets you to create secure hash values for data. It’s commonly used to:

  • Store passwords securely (hashed, not in plain text).
  • Check file integrity (make sure a file hasn’t changed).
  • Create unique IDs based on content.

Example: md5

import hashlib

text = "hello"
hash_object = hashlib.md5(text.encode())
print(hash_object.hexdigest())

Example: sha256

import hashlib

hash_object = hashlib.sha256("hello".encode())
print(hash_object.hexdigest())

Other available hash algorithms in hashlib:

blake2s

sha1

sha224

sha256

sha384

sha512

blake2b

Why Hashing Is Useful

Hashing is used in:

  • Caching.
  • Fast data retrieval (dictionaries, sets).
  • Database indexing.
  • Checking for duplicates.
  • Blockchain and cryptography.

Understanding it helps you to write better, faster, and safer code.

Hashable Objects in Python: Final Thoughts

When you are working with data structures in Python, you should have a proper command on python hashable types. Hashable objects keep your sets and dictionaries fast, predictable, and easy to use.

If you are ever unsure about it, ask yourself:


Is the object immutable?
Does it have a consistent hash value?
Will its contents change?

If the answer is no, then you are probably working with a hashable object.

Bonus Tip: Hash Values of Custom Classes

Do you want your own class to work in sets or dictionaries? Just define both __hash__() and __eq__() properly. And make sure the data you use to calculate the hash doesn’t change.

Please share you honest thoughts about the blogpost in comments!

Faq’s About Python Hashable Types

1. What are the 4 different data types in Python?

Common types are:

  1. int (numbers like 5, 10)
  2. float (decimal numbers like 3.14)
  3. str (text like “hello”)
  4. bool (True or False)

2. What does it mean for a type to be hashable?

  • It means the object can get a unique number (a hash) and be used in sets or as a dictionary key.
  • Hashable objects don’t change.

3. Is tuple hashable in Python?

  • Yes, tuples are hashable but only if all items inside them are hashable too.

4. What are unhashable types in Python?

  • These are types that can change, like:
    • lists
    • dictionaries
    • sets

They can’t be used as dictionary keys or in sets.

Stay ahead of the curve with the latest insights, tips, and trends in AI, technology, and innovation.

LEAVE A REPLY

Please enter your comment!
Please enter your name here