Typeerror: Unhashable Type: 'Numpy.Ndarray' in Python
Last Updated :
24 Apr, 2025
The Python library used for working with arrays is known as NumPy. Python provides various exceptions, including TypeError, which occurs when a specific operation is performed on an unsupported object type. One common TypeError encountered by users is 'TypeError: Unhashable Type: 'numpy.ndarray'.' In this article, we will discuss how to resolve this error.
What is Typeerror: Unhashable Type: 'Numpy.Ndarray'?
Whenever the user tries to use the NumPy array as a mutable object, whether it is a dictionary or a set, then we encounter the error Typeerror: Unhashable Type: 'Numpy.Ndarray'. It is because the value of the mutable object can be transformed later, thus they cannot be hashed. Hence, there is a need to get rid of this Typeerror.
The Typeerror: Unhashable Type: 'Numpy.Ndaaray' usually occurs in two circumstances:
- Using a NumPy array as a dictionary key
- Using a NumPy array as a set
What is hashability in Python?
The property of an object that allows the user to use any datatype as a key in a hash table is known as hashability. It is the mostly commonly used when handling dictionaries and sets in Python. The hashable objects are mutable, i.e., there value can be modified after creation, while the non-hashable objects are immutable, whose value cannot be modified after creation.
Examples of hashable objects:
Integers, double, string, tuple, etc. falls under the category of hashable objects.
Integers:
int_value=100
Double:
double_value=100.00
String:
string_text="Geeks For Geeks"
Tuple:
tuple_value = (100, 200, 300)
Examples of non-hashable objects:
List, dictionary, set, etc. falls under the category of non hashable objects.
List:
list_value=[100, 200, 300]
Set:
set_value={100, 200, 300}
Dictionary:
dictionary_value={'a': 100, 'b': 200}
How to fix the error?
Using NumPy ndarray in Sets
1. Example of adding a NumPy ndarray to a set
In this example, we have created a Numpy ndarray with values 50,60, 70 and a set. Further, we have added that Numpy array to the set. This gives us the Typerror.
Python3
# Import the numpy library
import numpy as np
# Creating a NumPy ndarray
arr = np.array([50,60,70])
# Creating a set
error_set = set()
# Adding NumPy array to set
error_set.add(arr)
# Print the ndarray
print(error_set)