What is ValueError: setting an array element with a sequence?
While programming in Python, especially Numpy a library in Python, programmers encounter an error called ValueError: setting an array element with a sequence. This error usually occurs when the Numpy array is not in sequence.
Let us see the details of this error and also its solution:
Code
import numpy as np
np.array([[[1, 2], [3, 4], [5, 6]], [[1], [2,4], [3,6]]], dtype=int)
Output
Traceback (most recent call last):
File "pyprogram.py", line 2, in <module>
np.array([[[1, 2], [3, 4], [5, 6]], [[1], [2,4], [3,6]]], dtype=int)
ValueError: setting an array element with a sequence.
Explanation
We can see that when this code is executed, the ValueError is raised. This is because the structure of the array is not correct. This two-dimensional array has individual arrays that have two elements each,
[[[1, 2], [3, 4], [5, 6]], [[1], [2,4], [3,6]]], except [1].
Correct Code
import numpy as np
np.array([ [[1, 2], [3, 4], [5, 6]], [ [1,3], [2,4], [3,6] ] ], dtype=int)
Explanation
Here, no error is encountered as all the individual sequences or arrays have two elements each. So, Numpy can successfully create an array.