Python ValueError: setting an array element with a sequence

In Python, if you are mainly working with numpy and creating a multi-dimensional array, you would have encountered valueerror: setting an array element with a sequence.

What is valueerror: setting an array element with a sequence?

A ValueError occurs when a function receives an argument of the correct type, but the value of the type is invalid. In this case, if the Numpy array is not in the sequence, you will get a Value Error. 

If you look at the example, the numpy array is 2-dimensional, but at the later stage, we have mixed with single-dimensional array also, and hence Python detects this as an inhomogeneous shape that means the structure of the array varies, and hence Python throws value error.

#Numpy array of different dimensions

import numpy as np
print(np.array([[[1, 2], [3, 4], [5, 6]], [[1],[2]]], dtype=int))

# Output
Traceback (most recent call last):
  File "c:\Projects\Tryouts\listindexerror.py", line 2, in <module>
    print(np.array([[[1, 2], [3, 4], [5, 6]], [[1],[2]]], dtype=int))
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.

Solution – By creating the same dimensional array and having identical array elements in each array will solve the problem as shown below. 

#Numpy array of same dimensions

import numpy as np
print(np.array([[[1, 2], [3, 4], [5, 6]]], dtype=int))

# Output
[[[1 2]
  [3 4]
  [5 6]]]

The other possibility where you get Value Error would be when you try to create an array with different types of elements; for instance, consider the below example where we have an array with float and string mixed, which again throws valueerror: could not convert string to float.

# Mutliple data type and dtype as float 

import numpy as np
print(np.array([55.55, 12.5, "Hello World"], dtype=float))

# Output
Traceback (most recent call last):
  File "c:\Projects\Tryouts\listindexerror.py", line 2, in <module>
    print(np.array([55.55, 12.5, "Hello World"], dtype=float))
ValueError: could not convert string to float: 'Hello World'

Solution – The solution of this is straightforward if you need either you declare only floating numbers inside an array or if you want both, then make sure that you change the dtype as an object instead of float as shown below.

# Changing the dtype as object and having multiple data type

import numpy as np
print(np.array([55.55, 12.5, "Hello World"], dtype=object))

# Output
[55.55 12.5 'Hello World']

Check out the below examples for more use cases and best practices while working with numpy arrays.

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
Leave a Reply

Your email address will not be published.

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

You May Also Like
Numpy Flatten

NumPy Flatten

Table of Contents Hide ndarray.flatten() method Syntaxndarray.flatten() method Parametersndarray.flatten() method Return ValueExample 1: How to flatten an array using NumPy ndarray.flatten() methodExample 2: Flattening an array using numpy.flatten() method with…
View Post
Python String Zfill()

Python String zfill()

Table of Contents Hide zfill() Syntaxzfill() Parameterszfill() Return ValueExample 1: How zfill() works in Python?Example 2: zfill() in case of Sign Prefix The Python String zfill() method is a built-in…
View Post
Numpy Mean

NumPy mean()

Table of Contents Hide NumPy mean() SyntaxNumPy mean() ParametersNumPy mean() Return ValueExample 1: Using the numpy.mean() method on a flattened arrayExample 2: Compute the mean of the array column-wise using…
View Post