DEV Community

himank
himank

Posted on

Hashable vs Immutable Objects in python

image
In Python, two important concepts to understand are hashable and immutable objects. These concepts determine how objects are stored and manipulated in memory, and they have a significant impact on the performance and functionality of our code.

Hashable Objects:

A hashable object is an object that has a hash value that never changes during its lifetime. This means that its value can be used as a key in a dictionary or as an element in a set. Examples of hashable objects in Python include integers, floating-point numbers, strings, and tuples (if they contain only hashable elements).

When you try to use an unhashable object as a key in a dictionary, Python will raise a TypeError. For example, lists are unhashable, so you cannot use them as keys in a dictionary:

d = {[1, 2, 3]: "list"}  # Raises TypeError
Enter fullscreen mode Exit fullscreen mode

Python has a built-in hash method ( hash() ) that can be used to compare other objects. If the hashable objects are equal then they have the same hash value.

print(hash(5))           # 5

print(hash("hello"))     # 6089416059157437065

print(hash(2+3))         # 5

print(hash("hello"))     # 6089416059157437065
Enter fullscreen mode Exit fullscreen mode

Immutable Objects:

An immutable object is an object whose state cannot be changed after it is created. This means that once you create an object, you cannot modify its value. Examples of immutable objects in Python include integers, floating-point numbers, and strings. All immutable built-in objects in Python are hashable like tuples while the mutable containers like lists and dictionaries are not hashable.

The advantage of using immutable objects is that they are safer to use in concurrent environments, as their state cannot be changed by another thread. This makes them easier to reason about and less prone to bugs.

On the other hand, mutable objects (such as lists and dictionaries) are more flexible and can be used for more complex data structures, but they can be harder to understand and debug when used in concurrent environments.

Checkout my other article about immutables in python.

Conclusion:

In conclusion, understanding the difference between hashable and immutable objects is crucial for writing efficient and maintainable Python code. When choosing between mutable and immutable objects, consider the requirements of your code and the trade-offs between flexibility and safety. In general, it is recommended to use immutable objects whenever possible, as they are easier to understand and less prone to bugs.

Top comments (0)