ValueError: setting an array element with a sequence (extended in NumPy 1.24+ to ... The requested array has an inhomogeneous shape after N dimensions) occurs when you pass a ragged/jagged nested sequence (lists of unequal lengths) to np.array() without dtype=object, or try to assign a list/array of multiple values into a single scalar cell of a typed NumPy array. Fix it by padding/normalizing inner sequences to uniform length, passing dtype=object if ragged nesting is intentional, or matching slice dimensions on the left-hand side during assignment.
Basic Example
import numpy as np
# 1. COMMON CAUSE A: Ragged / inhomogeneous nested list passed to np.array()
ragged = [[1, 2, 3], [4, 5]]
# np.array(ragged) # -> ValueError: setting an array element with a sequence.
# FIX A1: Pad shorter inner lists to equal length so the 2D shape (2, 3) is rectangular
max_len = max(len(row) for row in ragged)
padded = np.array([row + [0] * (max_len - len(row)) for row in ragged])
print(padded.shape) # Output: (2, 3)
# FIX A2: Pass dtype=object explicitly if you intentionally need variable-length rows
obj_arr = np.array(ragged, dtype=object)
# 2. COMMON CAUSE B: Assigning a sequence into a single scalar element slot
arr = np.zeros(3, dtype=float)
# arr[0] = [10, 20] # -> ValueError: setting an array element with a sequence
# FIX B: Assign to a slice matching the sequence length, OR create a 2D array
arr[0:2] = [10, 20]
print(arr) # Output: [10. 20. 0.]
Key Details & Root Causes
- 1. Why NumPy 1.24+ forbids automatic fallback to
dtype=object: Older NumPy versions (< 1.19) silently converted ragged lists likenp.array([[1, 2], [3]])into 1D arrays of Pythonlistobjects; NumPy 1.19–1.23 emitted aVisibleDeprecationWarning, and NumPy 1.24+ raisesValueErrorimmediately unless you passdtype=objectexplicitly. - 2. Mixing scalars and sequences at the same nesting level: Passing
[1, [2, 3]]or[(1, 2), 3]tonp.array()fails because element0has 0 dimensions while element1has 1 dimension. Ensure every item at a given depth has identical shape/length. - 3. Assigning a sequence to a scalar slot inside a loop or preallocated array:
- Creating
grid = np.zeros(5)makes a 1D array of 5 scalar floats. Writinggrid[i] = [1, 2, 3]fails becausegrid[i]holds a singlefloat64. Preallocate with the full target shape (grid = np.zeros((5, 3))) instead. - Similarly, returning a tuple or list
(x, y)insidenp.vectorize()whenotypesexpects a single scalar output raises this error unless you specifyotypes=[object]orsignature="()->(n)"innp.guvectorize.
- Creating
- 4. Fast zero-padding for variable-length 1D arrays (
itertools.zip_longest): When converting many uneven 1D sequences into a rectangular 2D NumPy matrix cleanly:from itertools import zip_longest import numpy as np sequences = [[1, 2, 3, 4], [5, 6], [7, 8, 9]] rectangular = np.array(list(zip_longest(*sequences, fillvalue=0))).T print(rectangular) # [[1 2 3 4] # [5 6 0 0] # [7 8 9 0]] - 5. Concatenating arrays of unequal lengths (
np.concatenatevs.np.array): If you want a single flat 1D array from variable-length lists rather than a 2D matrix, usenp.concatenate(sequences)instead ofnp.array(sequences).
Diagnostic & Fix Reference
| Failing Pattern | Root Cause | Clean Resolution |
|---|---|---|
np.array([[1, 2], [3, 4, 5]]) |
Inner sequences have unequal lengths (2 vs. 3) |
Pad to uniform length (zip_longest / list comprehension) or pass dtype=object. |
np.array([1, [2, 3]]) |
Mixed scalar and sequence at the same dimension | Wrap scalar as [1] + pad, or pass dtype=object. |
arr = np.zeros(4); arr[0] = [1, 2] |
Assigning a 2-element sequence into a scalar slot | Preallocate 2D (np.zeros((4, 2))) or assign to a slice (arr[0:2] =). |
np.array(list_of_uneven_arrays) (want 1D) |
Used np.array() instead of flattening/joining |
Use np.concatenate(list_of_uneven_arrays) to produce a flat 1D array. |
np.vectorize(lambda x: [x, x+1])(a) |
Function returns a sequence where a scalar is expected | Pass otypes=[object] or return stacked arrays directly with NumPy broadcasting. |
You must log in or register to comment.
