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)
2. Fixing the error by converting the ndarray to a tuple
A built in immutable datatype that is used to store sequence of values is known as tuple. In this method, we will see the way to fix the Typeerror: Unhashable Type: 'Numpy.Ndarray' by using a tuple.
Syntax:
tuple_arr = tuple(map(tuple, arr))
Here,
- arr: It is the Numpy Ndarray which is giving Typeerror.
Example:
In this example, we have created a NumPy array and then we have converted that array to a tuple to fix the Typeerror: Unhashable Type: 'Numpy.Ndarray'.
Python3
# Import the numpy library
import numpy as np
# Create a NumPy ndarray
arr = np.array([50, 60, 70])
# Convert the ndarray to a tuple
tuple_arr = tuple(map(tuple, arr))
# Creating a set
fixed_set = set()
# Adding numpy array to set
fixed_set.add(tuple_arr)
# Print the ndarray
print(fixed_set)
Output:
{(500, 600, 700): 'Value'}
Using NumPy ndarray in Dictionaries
1. Example of using NumPy ndarray as a key in a dictionary
In this example, we have defined a numpy ndarray with values 50,60 and 70 and a dictionary. Further, we have used numpy ndarray as a key in the dictionary.
Python3
# Import the numpy library
import numpy as np
# Creating a NumPy ndarray
arr = np.array([500, 600, 700])
# Using Numpy ndarray as a value
error_dict = { arr: 'key'}
# Print the ndarray
print(error_dict)
2. Fixing the error by using Numpy ndarray as a dictionary value
The Typeerror occurs when the element is used a key in the dictionary. Thus, in this method, we will fix the Typeerror: Unhashable Type: 'Numpy.Ndarray' by using it as a dictionary value.
Syntax:
my_dict = {'key': arr}
Here,
- arr: It is the Numpy Ndarray which is giving Typeerror.
Example:
In this example, we have created a numpy array and then used it a dictionary value to fix the Typeerror: Unhashable Type: 'Numpy.Ndarray'.
Python3
# Import the numpy library
import numpy as np
# Creating a NumPy ndarray
arr = np.array([500, 600, 700])
# Using Numpy ndarray as a value
fixed_dict = {'key': arr}
# Print the ndarray
print(fixed_dict)
Output:
{'key': array([500, 600, 700])}
Similar Reads
TypeError: unhashable type slice in Python
typeError is a common issue in Python that can arise due to various reasons. One specific TypeError that developers might encounter is the "Unhashable Type: 'Slice'". This error occurs when you try to use a slice object (created using the colon : notation) as a key in a dictionary or as an element i
5 min read
numpy.ndarray.view() in Python
numpy.ndarray.view() helps to get a new view of array with the same data. Syntax: ndarray.view(dtype=None, type=None)Parameters: dtype : Data-type descriptor of the returned view, e.g., float32 or int16. The default, None, results in the view having the same data-type as a. type : Python type, opti
3 min read
numpy.ndarray.resize() function - Python
numpy.ndarray.resize() function change shape and size of array in-place. Syntax : numpy.ndarray.resize(new_shape, refcheck = True) Parameters : new_shape :[tuple of ints, or n ints] Shape of resized array. refcheck :[bool, optional] If False, reference count will not be checked. Default is True. Ret
1 min read
NumPy Tutorial - Python Library
NumPy (short for Numerical Python ) is one of the most fundamental libraries in Python for scientific computing. It provides support for large, multi-dimensional arrays and matrices along with a collection of mathematical functions to operate on arrays.At its core it introduces the ndarray (n-dimens
3 min read
numpy.ndarray.fill() in Python
numpy.ndarray.fill() method is used to fill the numpy array with a scalar value. If we have to initialize a numpy array with an identical value then we use numpy.ndarray.fill(). Suppose we have to create a NumPy array a of length n, each element of which is v. Then we use this function as a.fill(v).
2 min read
numpy.ma.row_stack() in Python
numpy.ma.row_stack() : This function helps stacking arrays row wise in sequence vertically manner. Parameters : tup : sequence of ndarrays. 1D arrays must have same length, arrays must have the same shape along with all the axis. Result : Row-wise stacked arrays Code #1: Explaining row_stack() Pytho
1 min read
numpy.ndarray.flat() in Python
The numpy.ndarray.flat() function is used as a 1_D iterator over N-dimensional arrays. It is not a subclass of, Pythonâs built-in iterator object, otherwise it a numpy.flatiter instance. Syntax : numpy.ndarray.flat() Parameters : index : [tuple(int)] index of the values to iterate Return :  1-D i
3 min read
Python | Numpy ndarray.item()
With the help of numpy.ndarray.item() method, we can fetch the data elements that is found at the given index on numpy array. Remember we can give index as one dimensional parameter or can be two dimensional. Parameters: *args : Arguments (variable number and type) -> none: This argument only works
2 min read
PyTorch Tensor vs NumPy Array
PyTorch and NumPy can help you create and manipulate multidimensional arrays. This article covers a detailed explanation of how the tensors differ from the NumPy arrays. What is a PyTorch Tensor?PyTorch tensors are the data structures that allow us to handle multi-dimensional arrays and perform math
8 min read
numpy.array_repr() in Python
numpy.array_repr()function is used to convert an array to a string. Syntax : numpy.array_repr(arr, max_line_width=None, precision=None, suppress_small=None) Parameters : arr : [array_like] Input array. max_line_width : [int, optional] The maximum number of columns the string should span. Newline cha
2 min read