TypeError: unhashable type: 'numpy.ndarray'

The error message TypeError: unhashable type: numpy.ndarray indicates that you are attempting to use a NumPy ndarrayAn ndarray is a multi-dimensional array object in NumPy. in a data structure that requires hashable elements, such as a dictionary or a set. To better understand the error, it's essential first to grasp the concept of hashability in Python.

Hashability

In Python, hashable objects such as integers, booleans, strings, or tuples remain unchanged throughout their lifetime. This property enables Python to assign a unique hash value to each object, which is crucial for dictionaries to ensure unique keys and sets to maintain unique values.

Hashable data types

Non-Hashable Data Types

Integer

List

Boolean

Dictionary

String

Set

Tuple

NumPy ndarray

Code

Here's an example showing various types of objects, illustrating the distinction between hashable and non-hashable objects. The code aims to determine whether various data types are hashable or not.

import numpy as np
# Hashable objects
hashable_integer = 42
hashable_string = 'Hello, Educative!'
hashable_tuple = (1, 2, 3)
print(hash(hashable_integer))
print(hash(hashable_string))
print(hash(hashable_tuple))
#Non-hashable objects
non_hashable_arr = np.array([1,2,3,4])
non_hashable_list = [1, 2, 3]
non_hashable_dict = {'name': 'John', 'age': 25}
non_hashable_set = {1, 2, 3}
print(hash(non_hashable_arr))
  • Lines 410: The code defines hashable objects (integer, string, tuple) and displays their hash values using the hash() function.

  • Lines 12–18: When trying to compute the hash of a non-hashable object like a NumPy array, a TypeError is raised due to NumPy arrays' mutabilityMutable objects are those that can be modified or changed after they are created., making them ineligible for hashing.

Fixing the TypeError: unhashable type

The error arises when we use a NumPy array when data structures expect hashable types. It becomes necessary to convert the NumPy array into hashable types.

In the subsequent discussion, we will explore various scenarios where this error can occur and provide solutions to resolve it effectively.

Using a NumPy ndarray as a key in the dictionary

In Python, dictionary keys must be hashable. The error will appear when attempting to use a NumPy ndarray as a key in a Python dictionary.

Faulty code

The code snippet provided aims to verify whether an ndarray can be used as a key in a dictionary. It tests the feasibility of using an ndarray as a dictionary key.

import numpy as np
# Creating an ndarray
arr = np.array([1, 2, 3])
# Creating a dictionary with the ndarray as a key
my_dict = {arr: 'Value'}
print(my_dict) # Output: {array([1, 2, 3]): 'Value'}

The code attempts to use an ndarray as a key in a dictionary assignment. However, it raises an error because ndarrays are not hashable. To resolve the error, you can convert the ndarray to a hashable type, such as a tuple.

Fixed code

To resolve the TypeError: unhashable type: numpy.ndarray error, you can modify the code by converting the NumPy ndarray to a hashable type, like a tuple. The provided code snippet resolves the issue.

import numpy as np
# Creating a NumPy ndarray
arr = np.array([1, 2, 3])
# Converting the ndarray to a tuple
tuple_arr = tuple(arr)
# Creating a dictionary with the tuple as a key
my_dict = {tuple_arr: 'Value'}
print(my_dict) # Output: {(1, 2, 3): 'Value'}
  • Line 7: The NumPy ndarray arr is converted to a tuple tuple_arr using the tuple() constructor to resolve the issue

  • Lines 1012: Subsequently, the dictionary my_dict is created with the tuple as the key, ensuring error-free assignment, which converts the object into a hashable data type.

Including NumPy ndarray within a set

In Python, the elements of the set must be hashable. When attempting to use a NumPy ndarray as a set element, the error will appear.

Faulty Code

The code snippet provided aims to show whether an ndarray can be used as an element of a set or not.

import numpy as np
# Creating a NumPy ndarray
arr = np.array([[1, 2, 3],[4,5,6]])
# Creating a set and adding the tuple
my_set = set()
my_set.add(arr)
print(my_set) # Output:TypeError: unhashable type: 'numpy.ndarray'

The error occurs because, again, the NumPy ndarray is not in hashable type, so we will again use a tuple to convert the array into hashable type.

Fixed Code

To address the issue, we can convert the NumPy ndarray into a hashable type. The provided code snippet utilizes a map function to transform each 1D array into a tuple, making it a hashable type. This conversion helps in resolving the problem.

import numpy as np
# Creating a NumPy ndarray
arr = np.array([[1, 2, 3],[4,5,6]])
# Converting the ndarray to a tuple
tuple_arr = tuple(map(tuple, arr))
my_set = set()
my_set.add(tuple_arr)
print(my_set) # set([((1, 2, 3), (4, 5, 6))])
  • Line 7: We convert the ndarray arr to a tuple by using the map() function in combination with the tuple() constructor. The map() function applies the tuple() function to each row of the ndarray, resulting in a new iterable containing tuples.

  • Lines 10–13: A set named my_set is created, and the tuple_arr variable that holds the converted tuples is added to the set using the add() method. We will no longer see an error because the array was converted to a hashable type.

Conclusion

The error TypeError: unhashable type: 'numpy.ndarray' occurs when attempting to perform operations such as using an ndarray as a dictionary key or adding an ndarray object to a set.

In various scenarios, it is common to convert a 1D array into a tuple when encountering similar errors. For 2D arrays, we can convert each 1D array individually to tuples to mitigate the error.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved