Numpy Fix “ValueError: setting an array element with a sequence”

This guide teaches you how to fix the common error ValueError: setting array element with a sequence in Python/NumPy.

This error occurs because you have elements of different dimensions in the array. For example, if you have an array of arrays and one of the arrays has 2 elements and the other has 3, you’re going to see this error.

Let me show you how to fix it.

Cause 1: Mixing Arrays of Different Dimensions

ValueError: setting array element with a sequence because of mismatch in array lengths

One of the main causes for the ValueError: setting array element with a sequence is when you’re trying to insert arrays of different dimensions into a NumPy array.

For example:

import numpy as np

arr = np.array([[1,2], [1,2,3]], dtype=int)

print(arr)

Output:

ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 1 dimensions. The detected shape was (2,) + inhomogeneous part.

If you take a closer look at the error above, it states clearly that there’s an issue with the shape of the array. More specifically, the first array inside the arr has 2 elements ([1,2]) whereas the second array has 3 elements ([1,2,3]). To create an array, the number of elements of the inner arrays must match!

Solution

Let’s create arrays with an equal number of elements.

import numpy as np

numpy_array = np.array([[1, 2], [1, 2]], dtype=int)

print(numpy_array)

Output:

[[1 2]
 [1 2]]

This fixes the issue because now the number of elements in both arrays is the same—2.

Cause 2: Trying to Replace a Single Array Element with an Array

Replacing a single element in an array with an array causes error
Replacing a single element with an array won’t work.

Another reason why you might see the ValueError: setting array element with a sequence is if you try to replace a singular array element with an array.

For example:

import numpy as np

arr = np.array([1, 2, 3])

arr[0] = np.array([4, 5])

print(arr)

Output:

ValueError: setting an array element with a sequence.

In this piece of code, the issue is you’re trying to turn the first array element, 1, into an array [4,5]. NumPy expects the element to be a single number, not an array. This is what causes the error

Solution

Make sure to add singular values into the array in case it consists of individual values. Don’t try to replace a value with an array.

For example:

import numpy as np

arr = np.array([1, 2, 3])

arr[0] = np.array([4])

print(arr)

Output:

[4 2 3]

Thanks for reading. Happy coding!

Scroll to Top