The Python NumPy "ValueError: setting an array element with a sequence in Python" occurs when lists of different lengths are entered as objects in an array. To solve the error, enter either numbers separated by commas, or lists of the same lengths separated by commas.
Valid NumPy arrays can look like the following.
# ✅ A list of numbers, which can be integers or floats
numpy.array([1, 4, 56.7, 3, 8, 23423235, 4.8888])
# ✅ A list of arrays, that are all the same length, in this case, two
# This forms an array of arrays
numpy.array([[3, 5], [343, 5.44], [2, 9]])
You may be creating "jagged arrays," an array of sub-arrays, where all of the sub-arrays are not the same length. In these examples, the argument to numpy.array
contains lists of different lengths.
This will result in the "ValueError" message because the input list is not shaped like a "box" that can be turned into a multidimensional array.
# 🚫 A list of arrays, that are NOT all the same length
numpy.array([[1], [2, 3], [4, 5, 64]])
# 🚫 A list of arrays, that are all the same length, but one of the sub-arrays is not the same length
numpy.array([[1, 4], [2, 3], [5, [2, 6]]])
You may be creating an array with incompatible types. numpy.array
has a dtype
parameter which lets you specify the type of element the array will hold.
# 🚫 The dtype is "float", but the inputs to the array include strings
numpy.array([2, 45., "example"], dtype=float)
If you want a NumPy array to contain both strings and floats, use the dtype=object
paramter, which allows the array to hold arbitrary Python objects.
# ✅
numpy.array([45, 42.3, "hello"], dtype=object)
The Python NumPy "ValueError: setting an array element with a sequence in Python" occurs when lists of different lengths are entered as objects in an array. To solve the error, enter either numbers separated by commas, or lists of the same lengths separated by commas.
Related tutorials curated for you
Syntax Error: invalid syntax
IndexError: list index out of range
ModuleNotFoundError: No module named 'matplotlib' in Python
Flatten a list in Python
ModuleNotFoundError: No module named 'pip' in Python
How to fix: pandas data cast to numpy dtype of object. Check input data with np.asarray(data)
ModuleNotFoundError: No module named 'numpy' in Python
TypeError: a bytes-like object is required, not 'str'
ModuleNotFoundError: No module named 'pandas' in Python
Convert JSON to CSV in Python
How to fix: IndentationError expected an indented block in Python
SyntaxError: unexpected EOF while parsing