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:

Copynumpy.array([[1, 2], [2, 3, 4]])         # wrong!
Copynumpy.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:

Copynumpy.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:

Copynumpy.array([1.2, "abc"], dtype=object)
Answer from Sven Marnach on Stack Overflow
Top answer
1 of 11
401

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:

Copynumpy.array([[1, 2], [2, 3, 4]])         # wrong!
Copynumpy.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:

Copynumpy.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:

Copynumpy.array([1.2, "abc"], dtype=object)
2 of 11
95

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:

Copyimport 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:

Copyx = 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.

🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-fix-valueerror-setting-an-array-element-with-a-sequence
How to Fix ValueError: setting an array element with a sequence - GeeksforGeeks
July 23, 2025 - This error occurs when NumPy expects a single value like a number or string but receives a sequence like a list or array instead. It often happens with: ... NumPy cannot automatically convert these sequences into a fixed, uniform structure so ...
Discussions

ValueError: setting an array element with a sequence.
Hi, I am a fresh user of scvelo and thanks for providing this useful tool! I run into this bug Traceback (most recent call last): File "/Users/kfang/miniconda3/envs/scvelo/lib/python3.9/site-p... More on github.com
🌐 github.com
1
June 7, 2023
machine learning - Getting 'ValueError: setting an array element with a sequence.' when attempting to fit mixed-type data - Data Science Stack Exchange
I have already seen this, this and this question, but none of the suggestions seemed to fix my problem (so I have reverted them). I have the following code: nlp = spacy.load('en_core_web_sm') par... More on datascience.stackexchange.com
🌐 datascience.stackexchange.com
June 30, 2019
ValueError: setting an array element with a sequence
Im trying to training a Random Forest Classifier to predict movie success based on various features. Im using tmdb_5000_movies.csv data set. code as below df_movies = pd.read_csv(‘tmdb_5000_movies.csv’) df_credits= pd.read_csv(‘tmdb_5000_credits.csv’) df_movies.rename(columns={‘id’: ... More on discuss.python.org
🌐 discuss.python.org
4
0
June 9, 2024
python - Numpy ValueError: setting an array element with a sequence. This message may appear without the existing of a sequence? - Stack Overflow
Why do I get this error message? ValueError: setting an array element with a sequence. More on stackoverflow.com
🌐 stackoverflow.com
🌐
Reddit
reddit.com › r/learnpython › "valueerror: setting an array element with a sequence." when integrating with odeint
r/learnpython on Reddit: "ValueError: setting an array element with a sequence." when integrating with odeint
December 17, 2021 -

I'm trying to integrate some ordinary differential equations but I need some of the parameters to be a cosine function of time. While testing the code, I keep getting the above value error. I also posted this to r/learningpython but this sub seems like it may be more helpful!

Here's the code:

import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint
def vd(t):
return -(267 / 1440) * np.cos((2 * np.pi) / 365 * t) + (639 / 1440)

tmax = 2 * 365 # how long to run the system in days
t = np.arange(0.0, tmax, 1.0)

# define the constants
N = 3.295e8 # population of the US
theta = 0.8 # infectiousness
zeta = 0.75 # susceptibility
c = (N * 10 ** -5) / N # contact rate, depending on percentage of total population
alpha = theta * zeta * c
gamma = 0.1 # recovery rate, used often in class
rho = 0.2 # rate of loss of immunity
deltad = 0.1*vd(t) # rate of loss of Vitamin-D in body
# these are all the differential equations from simple SIR model
def deriv(y, t, alpha, gamma, rho):
S, I, R, D = y
dS = -alpha * I * S + rho * R
dI = alpha * I * S - gamma * I
dR = gamma * I - rho * R - rho * R * deltad
dD = deltad * (rho * R - S * L(t))
return dS, dI, dR, dD
# define some more initial conditions for integration
I0 = 1 # 1st person infected
R0 = 0 # 0 people recovered at first, obviously
S0 = N - I0 - R0
D0 = 0 # initial vitamin D in population, t=0 means January 1st
# initial conditions vector
y0 = S0, I0, R0, D0

ret = odeint(deriv, y0, t, args=(alpha, gamma, rho))
S, I, R, D = ret.T

Then I try to plot S, I, R, and D but that error pops up regarding the odeint line.

Those constants will probably change but I do need to input some stuff into dS, dI, dR, and dD that look like deltad and was hoping that someone on here with more python experience could help me.

Thank you!

🌐
GitHub
github.com › theislab › scvelo › issues › 1077
ValueError: setting an array element with a sequence. · Issue #1077 · theislab/scvelo
June 7, 2023 - Traceback (most recent call last): File "/Users/kfang/miniconda3/envs/scvelo/lib/python3.9/site-packages/IPython/core/interactiveshell.py", line 3508, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-6-595fdc5ca577>", line 1, in <module> scv.tl.velocity_graph(adata, n_jobs=1) File "/Users/kfang/miniconda3/envs/scvelo/lib/python3.9/site-packages/scvelo/tools/velocity_graph.py", line 363, in velocity_graph vgraph.compute_cosines(n_jobs=n_jobs, backend=backend) File "/Users/kfang/miniconda3/envs/scvelo/lib/python3.9/site-packages/scvelo/tools/velocity_graph.py", line 175, in compute_cosines res = parallelize( File "/Users/kfang/miniconda3/envs/scvelo/lib/python3.9/site-packages/scvelo/core/_parallelize.py", line 138, in wrapper res = np.array(res) if as_array else res ValueError: setting an array element with a sequence.
Author   KunFang93
🌐
Statology
statology.org › home › how to fix: valueerror: setting an array element with a sequence
How to Fix: ValueError: setting an array element with a sequence
October 22, 2021 - The error tells us exactly what we did wrong: We attempted to set one element in the NumPy array with a sequence of values.
Find elsewhere
🌐
Python.org
discuss.python.org › python help
ValueError: setting an array element with a sequence - Python Help - Discussions on Python.org
June 9, 2024 - Im trying to training a Random Forest Classifier to predict movie success based on various features. Im using tmdb_5000_movies.csv data set. code as below df_movies = pd.read_csv(‘tmdb_5000_movies.csv’) df_credits= pd.read_csv(‘tmdb_5000_credits.csv’) df_movies.rename(columns={‘id’: ...
Top answer
1 of 7
57

You're getting the error message

ValueError: setting an array element with a sequence.

because you're trying to set an array element with a sequence. I'm not trying to be cute, there -- the error message is trying to tell you exactly what the problem is. Don't think of it as a cryptic error, it's simply a phrase. What line is giving the problem?

kOUT[i]=func(TempLake[i],Z)

This line tries to set the ith element of kOUT to whatever func(TempLAke[i], Z) returns. Looking at the i=0 case:

In [39]: kOUT[0]
Out[39]: 0.0

In [40]: func(TempLake[0], Z)
Out[40]: array([ 0.,  0.,  0.,  0.])

You're trying to load a 4-element array into kOUT[0] which only has a float. Hence, you're trying to set an array element (the left hand side, kOUT[i]) with a sequence (the right hand side, func(TempLake[i], Z)).

Probably func isn't doing what you want, but I'm not sure what you really wanted it to do (and don't forget you can usually use vectorized operations like A*B rather than looping in numpy.) That should explain the problem, anyway.

2 of 7
38

It's a pity that both of the answers analyze the problem but didn't give a direct answer. Let's see the code.

Z = np.array([1.0, 1.0, 1.0, 1.0])  

def func(TempLake, Z):
    A = TempLake
    B = Z
    return A * B
Nlayers = Z.size
N = 3
TempLake = np.zeros((N+1, Nlayers))
kOUT = np.zeros(N + 1)

for i in xrange(N):
    # store the i-th result of
    # function "func" in i-th item in kOUT
    kOUT[i] = func(TempLake[i], Z)

The error shows that you set the ith item of kOUT(dtype:int) into an array. Here every item in kOUT is an int, can't directly assign to another datatype. Hence you should declare the data type of kOUT when you create it. For example, like:

Change the statement below:

kOUT = np.zeros(N + 1)

into:

kOUT = np.zeros(N + 1, dtype=object)

or:

kOUT = np.zeros((N + 1, N + 1))

All code:

import numpy as np
Z = np.array([1.0, 1.0, 1.0, 1.0])

def func(TempLake, Z):
    A = TempLake
    B = Z
    return A * B

Nlayers = Z.size
N = 3
TempLake = np.zeros((N + 1, Nlayers))

kOUT = np.zeros(N + 1, dtype=object)
for i in xrange(N):
    kOUT[i] = func(TempLake[i], Z)

Hope it can help you.

🌐
Edureka Community
edureka.co › home › community › categories › python › valueerror setting an array element with a...
ValueError setting an array element with a sequence | Edureka Community
April 30, 2022 - I am getting this error: File "mypath\mypythonscript.py", line 3484, in secondfunction RRDuringArray = ... explain to me how to fix this problem?
🌐
GoLinuxCloud
golinuxcloud.com › home › programming › fix "setting an array element with a sequence" in python (numpy valueerror explained + examples)
Fix "Setting an Array Element with a Sequence" in Python (NumPy ValueError Explained + Examples) | GoLinuxCloud
April 1, 2026 - This error occurs when NumPy receives inconsistent data, such as assigning a sequence (list/array) where a scalar is expected or when array shapes do not match. ... NumPy expects all elements to follow the same structure (shape), but you are ...
🌐
GitHub
github.com › numpy › numpy › issues › 6584
"setting an array element with a sequence" error could be improved. · Issue #6584 · numpy/numpy
October 29, 2015 - There was an error while loading. Please reload this page · This is a bit of a nitpick, but I think this would improve user-friendlyness. Currently np.asarray([[1, 2], [2, 3, 4]], dtype=np.float) yields "setting an array element with a sequence."
Author   amueller
🌐
Stack Overflow
es.stackoverflow.com › questions › 608935 › error-al-crear-un-array-setting-an-array-element-with-a-sequence
python - Error al crear un array: setting an array element with a sequence - Stack Overflow en español
Estas intentando crear un array que no tiene el mismo numero de elementos por dimension, es decir, que no es homogéneo. Por ejemplo: np.array([[[1], [0]], [[1, 1], [0, 1]]]). Puedes crear un array de listas con training = np.array(training, ...
🌐
PyMC Discourse
discourse.pymc.io › questions
ValueError: setting an array element with a sequence - Questions - PyMC Discourse
December 3, 2018 - Description of my problem: This problem may sound silly, but I can’t fix it. Hope get your help. Thank you. “k_s[0] = k ValueError: setting an array element with a sequence.” Description of my code: object_t_change = theano.shared(t_change, name='t_change') object_A = theano.shared(A, name='A') object_X_new = theano.shared(X_new, name='X') object_t = theano.shared(t, name='t') object_y = theano.shared(y, name='y') object_tau = theano.shared(tau, name='tau') objec...
🌐
Its Linux FOSS
itslinuxfoss.com › home › python
Valueerror: Setting an Array Element With a Sequence – Its Linux FOSS
March 22, 2023 - While working with arrays in Python, you may have encountered the error “ValueError: setting an array element/items with a sequence”. The error occurs when you try to assign a sequence of values (such as a list or tuple) to an array element.
🌐
GitHub
github.com › OpenTalker › SadTalker › issues › 767
[Issue] ValueError: setting an array element with a sequence. · Issue #767 · OpenTalker/SadTalker
December 31, 2023 - [Issue] ValueError: setting an array element with a sequence.#767 · Copy link · siddharthahiremath · opened · on Dec 31, 2023 · Issue body actions ·
Author   siddharthahiremath
🌐
GitHub
github.com › cvxpy › cvxpy › issues › 1257
ValueError: setting an array element with a sequence. · Issue #1257 · cvxpy/cvxpy
March 1, 2021 - Describe the bug In my cost function a use as an intermediate step a numpy matrix and it results in the following error: ValueError: setting an array element with a sequence. To Reproduce def fancy_6D_lin(image,x,y,theta_1,theta_2): "pos...
Author   brunoeducsantos
🌐
Reddit
reddit.com › r/learnpython › valueerror: setting an array element with a sequence
r/learnpython on Reddit: ValueError: setting an array element with a sequence
April 15, 2024 -

From two different homeworks, dy(t, x) is a Jacobi matrix of a model function for a Gauss Newton algorithm.

Why does this function cause an error

def dy(t, x):

a1, a2, a3, a4, a5, a6, a7 = x

return np.array([1 / ( 1 + ((t - a6) / (a7 / 2))**2),

1,

t*1,

t**2,

t**3,

a1*(2*((t-a6)/(a7**2/4)) / (1+((t-a6)/(a7/2))**2)**2),

a1*(2/a7*((t-a6)/(a7/2)) / (1+((t-a6)/(a7/2))**2)**2)], dtype=float).T

x0 = np.array([2.06, 0.74, 8.92, -24.45, 17.84, 0.35, 0.1], dtype=float)

print("shape: ", dy(data[:,0],x0).shape)

print("dy:", dy(data[:,0], x0))

ValueError: setting an array element with a sequence. The requested array has an inhomogeneous shape after 1 dimensions. The detected shape was (7,) + inhomogeneous part.

But this one does not?

def dy(t,x):

a, tau, omega, phi = x

return np.array([np.exp(-tau*t)*np.sin(omega*t+phi), #da/dt

-t*a*np.exp(-tau*t)*np.sin(omega*t+phi), #dtau/dt

t*a*np.exp(-tau*t)*np.cos(omega*t+phi), #domega/dt

a*np.exp(-tau*t)*np.cos(omega*t+phi)]).T #dphi/dt

x0 = np.array([1, 1, 3, 1],dtype=float)

dy(data[:,0], x0)

print("shape: ", dy(data[:,0],x0).shape)

Output: shape: (10, 4)

🌐
ProgrammingR
programmingr.com › home
Python Error: valueerror: setting an array element with a sequence - ProgrammingR
June 10, 2021 - The solution to the valueerror: setting an array element with a sequence involves adjusting the scalar, vector, or other object that is causing the error message.
🌐
Streamlit
discuss.streamlit.io › random
ValueError: setting an array element with a sequence - Random - Streamlit
March 28, 2023 - Summary I am trying to deploy my model but I am getting this error listed in the title. I tried removing brackets from the list in line 110 and that didn’t work. Steps to reproduce Code snippet: Traceback (most recent…