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

ValueError: setting an array element with a sequence usually occurs when trying to assign a sequence of values to a single array element. To fix this error, you should ensure that the number of elements in the array and the number of elements in the sequence match. If they don’t, you should convert the sequence into a single element by using a loop or a comprehension. If that isn’t possible, you should consider using a different data structure such as a list or a dictionary.


One error you may encounter when using Python is:

ValueError: setting an array element with a sequence.

This error typically occurs when you attempt to cram several numbers into a single position in a NumPy array.

The following example shows how to fix this error in practice.

How to Reproduce the Error

Suppose we have the following NumPy array:

import numpy as np

#create NumPy array
data = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])

Now suppose we attempt to cram two numbers into the first position of the array:

#attempt to cram values '4' and '5' both into first position of NumPy array
data[0] = np.array([4,5])

ValueError: setting an array element with a sequence.

The error tells us exactly what we did wrong: We attempted to set one element in the NumPy array with a sequence of values.

In particular, we attempted to cram the values ‘4’ and ‘5’ both into the first position of the NumPy array.

This isn’t possible to do, so we receive an error.

How to Fix the Error

The way to fix this error is to simply assign one value into the first position of the array:

#assign the value '4' to the first position of the array
data[0] = np.array([4])

#view updated array
data

array([ 4,  2,  3,  4,  5,  6,  7,  8,  9, 10])

Notice that we don’t receive any error.

If we actually do want to assign two new values to elements in the array, we need to use the following syntax:

#assign the values '4' and '5' to the first two positions of the array
data[0:2] = np.array([4, 5])

#view updated array
data

array([ 4,  5,  3,  4,  5,  6,  7,  8,  9, 10])

Notice that the first two values were changed in the array while all of the other values remained the same.

The following tutorials explain how to fix other common errors in Python:

x