How to Fix ValueError: setting an array element with a sequence

The ValueError: setting an array element with a sequence error occurs when you try to assign a value to an element in an array, but the value is a sequence rather than a single value.

import numpy as np

arr = np.zeros((2, 2))

arr[0, 0] = [11, 21, 19]

print(arr)

Output

ValueError: setting an array element with a sequence.

The ValueError is raised because we are trying to assign a list – a sequence to an element in the array, but an element can only store a single value.

How to fix ValueError: setting an array element with a sequence

Assign a single value to each element in the array to fix ValueError: setting an array element with a sequence error in Python.

import numpy as np

arr = np.zeros((2, 2))

arr[0, 0] = 19

print(arr)

Output

[[19. 0.]
[ 0. 0.]]

In this example, we assign the value “19” to the first element of the array, which is why it does not throw any error.

If you are creating a NumPy array with different types of elements in it, you will probably get TypeError. If you mix an integer with a float value or an integer with a string, you will get ValueError.

And we solved the setting of an array element with a sequence error.

That’s pretty much it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.