Search code examples
pythonarraysnumpyslicevalueerror

ValueError: setting an array element with a sequence


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.

Solution

  • 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)