Why do the following code samples:
np.array([[1, 2], [2, 3, 4]])
np.array([1.2, "abc"], dtype=float)
…all give the following error?
ValueError: setting an array element with a sequence.
![]()
Mateen Ulhaq
24k18 gold badges97 silver badges132 bronze badges
asked Jan 12, 2011 at 21:58
1
Possible reason 1: trying to create a jagged array
You may be creating an array from a list that isn’t shaped like a multi-dimensional array:
numpy.array([[1, 2], [2, 3, 4]]) # wrong!
numpy.array([[1, 2], [2, [3, 4]]]) # wrong!
In these examples, the argument to numpy.array contains sequences of different lengths. Those will yield this error message because the input list is not shaped like a «box» that can be turned into a multidimensional array.
Possible reason 2: providing elements of incompatible types
For example, providing a string as an element in an array of type float:
numpy.array([1.2, "abc"], dtype=float) # wrong!
If you really want to have a NumPy array containing both strings and floats, you could use the dtype object, which allows the array to hold arbitrary Python objects:
numpy.array([1.2, "abc"], dtype=object)
![]()
Mateen Ulhaq
24k18 gold badges97 silver badges132 bronze badges
answered Jan 12, 2011 at 23:51
Sven MarnachSven Marnach
569k118 gold badges937 silver badges837 bronze badges
0
The Python ValueError:
ValueError: setting an array element with a sequence.
Means exactly what it says, you’re trying to cram a sequence of numbers into a single number slot. It can be thrown under various circumstances.
1. When you pass a python tuple or list to be interpreted as a numpy array element:
import numpy
numpy.array([1,2,3]) #good
numpy.array([1, (2,3)]) #Fail, can't convert a tuple into a numpy
#array element
numpy.mean([5,(6+7)]) #good
numpy.mean([5,tuple(range(2))]) #Fail, can't convert a tuple into a numpy
#array element
def foo():
return 3
numpy.array([2, foo()]) #good
def foo():
return [3,4]
numpy.array([2, foo()]) #Fail, can't convert a list into a numpy
#array element
2. By trying to cram a numpy array length > 1 into a numpy array element:
x = np.array([1,2,3])
x[0] = np.array([4]) #good
x = np.array([1,2,3])
x[0] = np.array([4,5]) #Fail, can't convert the numpy array to fit
#into a numpy array element
A numpy array is being created, and numpy doesn’t know how to cram multivalued tuples or arrays into single element slots. It expects whatever you give it to evaluate to a single number, if it doesn’t, Numpy responds that it doesn’t know how to set an array element with a sequence.
answered Nov 25, 2017 at 4:40
![]()
Eric LeschinskiEric Leschinski
146k95 gold badges412 silver badges332 bronze badges
0
In my case , I got this Error in Tensorflow , Reason was i was trying to feed a array with different length or sequences :
example :
import tensorflow as tf
input_x = tf.placeholder(tf.int32,[None,None])
word_embedding = tf.get_variable('embeddin',shape=[len(vocab_),110],dtype=tf.float32,initializer=tf.random_uniform_initializer(-0.01,0.01))
embedding_look=tf.nn.embedding_lookup(word_embedding,input_x)
with tf.Session() as tt:
tt.run(tf.global_variables_initializer())
a,b=tt.run([word_embedding,embedding_look],feed_dict={input_x:example_array})
print(b)
And if my array is :
example_array = [[1,2,3],[1,2]]
Then i will get error :
ValueError: setting an array element with a sequence.
but if i do padding then :
example_array = [[1,2,3],[1,2,0]]
Now it’s working.
answered Apr 2, 2018 at 19:20
![]()
Aaditya UraAaditya Ura
11.9k7 gold badges49 silver badges87 bronze badges
0
for those who are having trouble with similar problems in Numpy, a very simple solution would be:
defining dtype=object when defining an array for assigning values to it. for instance:
out = np.empty_like(lil_img, dtype=object)
answered Aug 11, 2018 at 6:41
![]()
Adam LiuAdam Liu
1,27813 silver badges17 bronze badges
1
In my case, the problem was another. I was trying convert lists of lists of int to array. The problem was that there was one list with a different length than others. If you want to prove it, you must do:
print([i for i,x in enumerate(list) if len(x) != 560])
In my case, the length reference was 560.
answered Mar 14, 2018 at 17:56
In my case, the problem was with a scatterplot of a dataframe X[]:
ax.scatter(X[:,0],X[:,1],c=colors,
cmap=CMAP, edgecolor='k', s=40) #c=y[:,0],
#ValueError: setting an array element with a sequence.
#Fix with .toarray():
colors = 'br'
y = label_binarize(y, classes=['Irrelevant','Relevant'])
ax.scatter(X[:,0].toarray(),X[:,1].toarray(),c=colors,
cmap=CMAP, edgecolor='k', s=40)
answered Feb 28, 2019 at 18:54
![]()
Max KleinerMax Kleiner
1,3761 gold badge13 silver badges14 bronze badges
1
When the shape is not regular or the elements have different data types, the dtype argument passed to np.array only can be object.
import numpy as np
# arr1 = np.array([[10, 20.], [30], [40]], dtype=np.float32) # error
arr2 = np.array([[10, 20.], [30], [40]]) # OK, and the dtype is object
arr3 = np.array([[10, 20.], 'hello']) # OK, and the dtype is also object
«
answered Jul 2, 2020 at 14:55
![]()
1
In my case, I had a nested list as the series that I wanted to use as an input.
First check: If
df['nestedList'][0]
outputs a list like [1,2,3], you have a nested list.
Then check if you still get the error when changing to input df['nestedList'][0].
Then your next step is probably to concatenate all nested lists into one unnested list, using
[item for sublist in df['nestedList'] for item in sublist]
This flattening of the nested list is borrowed from How to make a flat list out of list of lists?.
answered Aug 3, 2020 at 18:41
![]()
questionto42questionto42
6,7194 gold badges53 silver badges86 bronze badges
The error is because the dtype argument of the np.array function specifies the data type of the elements in the array, and it can only be set to a single data type that is compatible with all the elements. The value «abc» is not a valid float, so trying to convert it to a float results in a ValueError. To avoid this error, you can either remove the string element from the list, or choose a different data type that can handle both float values and string values, such as object.
numpy.array([1.2, "abc"], dtype=object)
answered Feb 2 at 15:44
![]()
In this article, we will discuss how to fix ValueError: setting array element with a sequence using Python.
Error which we basically encounter when we using Numpy library is ValueError: setting array element with a sequence. We face this error basically when we creating array or dealing with numpy.array.
This error occurred because of when numpy.array creating array with given value but the data-type of value is not same as data-type provided to numpy.
Steps needed to prevent this error:
- Easiest way to fix this problem is to use the data-type which support all type of data-type.
- Second way to fix this problem is to match the default data-type of array and assigning value.
Method 1: Using common data-type
Example : Program to show error code:
Python
import numpy
array1 = [1, 2, 4, [5, [6, 7]]]
Data_type = int
np_array = numpy.array(array1, dtype=Data_type)
print(np_array)
Output:
File “C:UserscomputersDownloadshe.py”, line 13, in <module>
np_array = numpy.array(array1,dtype=Data_type);
ValueError: setting an array element with a sequence.
We can fix this error if we provide the data type which support all data-type to the element of array:
Syntax:
numpy.array( Array ,dtype = Common_DataType );
Example: Fixed code
Python
import numpy
array1 = [1, 2, 4, [5, [6, 7]]]
Data_type = object
np_array = numpy.array(array1, dtype=Data_type)
print(np_array)
Output:
[1 2 4 list([5, [6, 7]])]
Method 2: By matching default data-type of value and Array
Example: Program to show error
Python
import numpy
array1 = ["Geeks", "For"]
Data_type = str
np_array = numpy.array(array1, dtype=Data_type)
np_array[1] = ["for", "Geeks"]
print(np_array)
Output:
File “C:UserscomputersDownloadshe.py”, line 15, in <module>
np_array[1] = [“for”,”Geeks”];
ValueError: setting an array element with a sequence
Here we have seen that this error is cause because we are assigning array as a element to array which accept string data-type. we can fix this error by matching the data-type of value and array and then assign it as element of array.
Syntax:
if np_array.dtype == type( Variable ):
expression;
Example: Fixed code
Python
import numpy
array1 = ["Geeks", "For"]
Data_type = str
np_array = numpy.array(array1, dtype=Data_type)
Variable = ["for", "Geeks"]
if np_array.dtype == type(Variable):
np_array[1] = Variable
else:
print("Variable value is not the type of numpy array")
print(np_array)
Output:
Variable value is not the type of numpy array ['Geeks' 'For']
Last Updated :
10 Feb, 2022
Like Article
Save Article
17 авг. 2022 г.
читать 1 мин
Одна ошибка, с которой вы можете столкнуться при использовании Python:
ValueError : setting an array element with a sequence.
Эта ошибка обычно возникает, когда вы пытаетесь втиснуть несколько чисел в одну позицию в массиве NumPy.
В следующем примере показано, как исправить эту ошибку на практике.
Как воспроизвести ошибку
Предположим, у нас есть следующий массив NumPy:
import numpy as np
#create NumPy array
data = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
Теперь предположим, что мы пытаемся втиснуть два числа в первую позицию массива:
#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.
Ошибка говорит нам, что именно мы сделали неправильно: мы попытались установить один элемент в массиве NumPy с последовательностью значений.
В частности, мы попытались втиснуть значения «4» и «5» в первую позицию массива NumPy.
Это невозможно сделать, поэтому мы получаем ошибку.
Как исправить ошибку
Способ исправить эту ошибку — просто присвоить одно значение первой позиции массива:
#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])
Обратите внимание, что мы не получаем никаких ошибок.
Если мы действительно хотим присвоить два новых значения элементам массива, нам нужно использовать следующий синтаксис:
#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])
Обратите внимание, что первые два значения в массиве были изменены, а все остальные значения остались прежними.
Дополнительные ресурсы
В следующих руководствах объясняется, как исправить другие распространенные ошибки в Python:
Как исправить KeyError в Pandas
Как исправить: ValueError: невозможно преобразовать число с плавающей запятой NaN в целое число
Как исправить: ValueError: операнды не могли транслироваться вместе с фигурами
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

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

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!
Read Also
Python Tips and Tricks
About the Author
-
I’m an entrepreneur and a blogger from Finland. My goal is to make coding and tech easier for you with comprehensive guides and reviews.
Recent Posts
Introduction
In python, we have discussed many concepts and conversions. In this tutorial, we will be discussing the concept of setting an array element with a sequence. When we try to access some value with the right type but not the correct value, we encounter this type of error. In this tutorial, we will be discussing the concept of ValueError: setting an array element with a sequence in Python.
What is Value Error?
A ValueError occurs when a built-in operation or function receives an argument with the right type but an invalid value. A value is a piece of information that is stored within a certain object.
In python, we often encounter the error as ValueError: setting an array element with a sequence is when we are working with the numpy library. This error usually occurs when the Numpy array is not in sequence.
What Causes Valueerror: Setting An Array Element With A Sequence?
Python always throws this error when you are trying to create an array with a not properly multi-dimensional list in shape. The second reason for this error is the type of content in the array. For example, define the integer array and inserting the float value in it.
Examples Causing Valueerror: Setting An Array Element With A Sequence
Here, we will be discussing the different types of causes through which this type of error gets generated:
1. Array Of A Different Dimension
Let us take an example, in which we are creating an array from the list with elements of different dimensions. In the code, you can see that you have created an array of two different dimensions, which will throw an error as ValueError: setting an array element with a sequence.
import numpy as np print(np.array([[1, 2,], [3, 4, 5]],dtype = int))
Output:

Explanation:
- Firstly, we have imported the numpy library with an alias name as np.
- Then, we will be making the array of two different dimensions with the data type of integer from the np.array() function.
- The following code will result in the error as Value Error as we cannot access the different dimensions array.
- At last, you can see the output as an error.
Solution Of An Array Of A Different Dimension
If we try to make the length of both the arrays equal, then we will not encounter any error. So the code will work fine.
import numpy as np print(np.array([[1, 2, 5], [3, 4, 5]],dtype = int))
Output:

Explanation:
- Firstly, we have imported the numpy library with an alias name as np.
- Then, we will make the different dimension array into the same dimension array to remove the error.
- At last, we will try to print the output.
- Hence, you can see the output without any error.
Also, Read | [Solved] IndentationError: Expected An Indented Block Error
2. Different Type Of Elements In An Array
Let us take an example, in which we are creating an array from the list with elements of different data types. In the code, you can see that you have created an array of multiple data types values than the defined data type. If we do this, there will be an error generated as ValueError: setting an array element with a sequence.
import numpy as np print(np.array([2.1, 2.2, "Ironman"], dtype=float))
Output:

Explanation:
- Firstly, we have imported the numpy library with an alias name as np.
- Then, we will be making the array of two different data types with the data type as a float from the np.array() function.
- The array contains two data types, i.e., float and string.
- The following code will result in the error as Value Error as we cannot write the different data types values as the one data type of array.
- Hence, you can see the output as Value Error.
Solution Of Different Type Of Elements In An Array
If we try to make the data type unrestricted, we should use dtype = object, which will help you remove the error.
import numpy as np print(np.array([2.1, 2.2, "Ironman"], dtype=object))
Output:

Explanation:
- Firstly, we have imported the numpy library with an alias name as np.
- Then, if we want to access the different data types values in a single array so, we can set the dtype value as an object which is an unrestricted data type.
- Hence, you can see the correct output, and the code runs correctly without giving any error.
Also, Read | [Solved] TypeError: String Indices Must be Integers
3. Valueerror Setting An Array Element With A Sequence Pandas
In this example, we will be importing the pandas’ library. Then, we will be taking the input from the pandas dataframe function. After that, we will print the input. Then, we will update the value in the list and try to print we get an error.
import pandas as pd output = pd.DataFrame(data = [[800.0]], columns=['Sold Count'], index=['Project1']) print (output.loc['Project1', 'Sold Count']) output.loc['Project1', 'Sold Count'] = [400.0] print (output.loc['Project1', 'Sold Count'])
Output:

Solution Of Value Error From Pandas
If we dont want any error in the following code we need to make the data type as object.
import pandas as pd output = pd.DataFrame(data = [[800.0]], columns=['Sold Count'], index=['Project1']) print (output.loc['Project1', 'Sold Count']) output['Sold Count'] = output['Sold Count'].astype(object) output.loc['Project1','Sold Count'] = [1000.0,800.0] print(output)
Output:

Also, Read | How to Solve TypeError: ‘int’ object is not Subscriptable
4. ValueError Setting An Array Element With A Sequence in Sklearn
Sklearn is a famous python library that is used to execute machine learning methods on a dataset. From regression to clustering, this module has all methods which are needed.
Using these machine learning models over the 2D arrays can sometimes cause a huge ValueError in the code. If your 2D array is not uniform, i.e., if several elements in all the sub-arrays are not the same, it’ll throw an error.
Example Code –
import numpy as np from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler from sklearn.svm import SVC X = np.array([[-1, 1], [2, -1], [1, -1], [2]]) y = np.array([1, 2, 2, 1]) clf = make_pipeline(StandardScaler(), SVC(gamma='auto')) clf.fit(X, y)
Here, the last element in the X array is of length 1, whereas all other elements are of length 2. This will cause the SVC() to throw an error ValueError – Setting an element with a sequence.
Solution –
The solution to this ValueError in Sklearn would be to make the length of arrays equal. In the following code, we’ve changed all the lengths to 2.
import numpy as np from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler from sklearn.svm import SVC X = np.array([[-1, 1], [2, -1], [1, -1], [2, 1]]) y = np.array([1, 2, 2, 1]) clf = make_pipeline(StandardScaler(), SVC(gamma='auto')) clf.fit(X, y)
Also, Read | Invalid literal for int() with base 10 | Error and Resolution
5. ValueError Setting An Array Element With A Sequence in Tensorflow
In Tensorflow, the input shapes have to be correct to process the data. If the shape of every element in your array is not of equal length, you’ll get a ValueError.
Example Code –
import tensorflow as tf import numpy as np # Initialize two arrays x1 = tf.constant([1,2,3,[4,1]]) x2 = tf.constant([5,6,7,8]) # Multiply result = tf.multiply(x1, x2) tf.print(result)
Here the last element of the x1 array has length 2. This causes the tf.multiple() to throw a ValueError.
Solution –
The only solution to fix this is to ensure that all of your array elements are of equal shape. The following example will help you understand it –
import tensorflow as tf import numpy as np # Initialize two arrays x1 = tf.constant([1,2,3,1]) x2 = tf.constant([5,6,7,8]) # Multiply result = tf.multiply(x1, x2) tf.print(result)
6. ValueError Setting An Array Element With A Sequence in Keras
Similar error in Keras can be observed when an array with different lengths of elements are passed to regression models. As the input might be a mixture of ints and lists, this error may arise.
Example Code –
model = Sequential() model.add(Dense(12, input_dim=8, activation='relu')) model.add(Dense(8, activation='relu')) model.add(Dense(1, activation='sigmoid')) # Compile the model model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) # Fit the model model.fit(X, y, epochs=150, batch_size=10) >>> ValueError: setting an array element with a sequence.
Here the array X contains a mixture of integers and lists. Moreover, many elements in this array are not fully filled.
Solution –
The solution to this error would be flattening your array and reshaping it to the desired shape. The following transformation will help you to achieve it. keras.layers.Flatten and pd.Series.tolist() will help you to achieve it.
model = Sequential() model.add(Flatten(input_shape=(2,2))) model.add(Dense(12, input_dim=8, activation='relu')) model.add(Dense(8, activation='relu')) model.add(Dense(1, activation='sigmoid')) # Compile the model model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) # Fit the model X = X.tolist() model.fit(X, y, epochs=150, batch_size=10)
Also, Read | How to solve Type error: a byte-like object is required not ‘str’
Conclusion
In this tutorial, we have learned about the concept of ValueError: setting an array element with a sequence in Python. We have seen what value Error is? And what is ValueError: setting an array element with a sequence? And what are the causes of Value Error? We have discussed all the ways causing the value Error: setting an array element with a sequence with their solutions. All the examples are explained in detail with the help of examples. You can use any of the functions according to your choice and your requirement in the program.
However, if you have any doubts or questions, do let me know in the comment section below. I will try to help you as soon as possible.
FAQs
1. How Does ValueError Save Us From Incorrect Data Processing?
We will understand this with the help of small code snippet:
while True:
try:
n = input("Please enter an integer: ")
n = int(n)
break
except ValueError:
print("No valid integer! Please try again ...")
print("Great, you successfully entered an integer!")
Input:
Firstly, we will pass 10.0 as an integer and then 10 as the input. Let us see what the output comes.
Output:

Now you can see in the code. When we try to enter the float value in place of an integer value, it shows me a value error which means you can enter only the integer value in the input. Through this, ValueError saves us from incorrect data processing as we can’t enter the wrong data or input.
2. We don’t declare a data type in python, then why is this error arrises in initializing incorrect datatype?
In python, We don’t have to declare a datatype. But, when the ValueError arises, that means there is an issue with the substance of the article you attempted to allocate the incentive to. This is not to be mistaken for types in Python. Hence, Python ValueError is raised when the capacity gets a contention of the right kind; however, it an unseemly worth it.

