You must have come across the terms Hashable and Mutability before. They are common to most Programming Languages. In this article, we will be discussing both terms. Although I’ll be using Python to explain the terms, the terms mean the same thing in other languages as well.
Mutability
When we create an object in Python, it is assigned a memory location. The value of the object is stored in this memory location. If we are allowed to update the value at this memory location, the object is said to be Mutable. If we are not allowed to update the value, the object is said to be Immutable. In Python Lists, Dictionaries and Sets are mutable objects while String, Boolean, Integer, Float, Tuples, and frozen Sets are immutable.
Do Not Confuse Mutability and Re-assignment. Irrespective of whether an object is mutable or not, it can always be re-assigned. In doing so, the memory location of the object changes. We can use the built-in id() method to get the memory location of an object.
Although a list is mutable, if we re-assign some value to it, the memory location of the list changes. It is the same case for an immutable object like a string.
When dealing with strings, it’s pretty easy to get confused with its mutability since you can append characters to it using +=. However, in doing so the memory location changes.
Since a list is mutable, if we append a value to it, the memory location still stays the same.
Hashable
An object is said to be hashable if we can have a hash value associate with it. A hash value is nothing but a numeric value of fixed length which can be used to uniquely identify data. What this means is that a hashable object is an object which can be mapped to a unique numerical value.
Consider the case where the fingerprint is some complex object. The fingerprint has a hash value associated with it. If we were given a bunch of fingerprints and ask to search for a specific fingerprint, it would take a lot of time. However if we knew the numerical value, i.e the hash of the fingerprint we want to search and has values of all the fingerprints in our database, we could easily compare the numbers.
The hash value is stored in a hexadecimal format, hence it has letters but it is a numerical value.
If an object is hashable, it can be used as a key for a dictionary. A dictionary is also called a hashmap. Every key in the dictionary has a hash value associated with it, these hash values result in an O(1) lookup time for a dictionary.
In python, lists, sets, and dictionaries are not hashable while String, Boolean, Integer, Float, Tuples, and frozen Sets are hashable.
Summary
- An object is said to be mutable if its value can be updated, not re-assigned after it is created.
- An object is said to be hashable if it can have a hash value associated with it