pandas-dev/pandas · error · ValueError
setting an array element with a sequence.
Error message
setting an array element with a sequence.
What it means
StringArray.__setitem__ raises ValueError('setting an array element with a sequence.') when a scalar key (single integer/position) is paired with a non-scalar value. You cannot store a list/array into a single slot of a 1-D string array.
Source
Thrown at pandas/core/arrays/string_.py:879
value = np.asarray(value)
if len(value) and not lib.is_string_array(value, skipna=True):
raise TypeError(
"Invalid value for dtype 'str'. Value should be a "
"string or missing value (or array of those)."
)
return value
def __setitem__(self, key, value) -> None:
if self._readonly:
raise ValueError("Cannot modify read-only array")
value = self._validate_setitem_value(value)
key = check_array_indexer(self, key)
scalar_key = lib.is_scalar(key)
scalar_value = lib.is_scalar(value)
if scalar_key and not scalar_value:
raise ValueError("setting an array element with a sequence.")
if not scalar_value:
if value.dtype == self.dtype:
value = value._ndarray
else:
value = np.asarray(value)
mask = isna(value)
if mask.any():
value = value.copy()
value[isna(value)] = self.dtype.na_value
super().__setitem__(key, value)
def _putmask(self, mask: npt.NDArray[np.bool_], value) -> None:
# the super() method NDArrayBackedExtensionArray._putmask uses
# np.putmask which doesn't properly handle None/pd.NA, so using the
# base class implementation that uses __setitem__
ExtensionArray._putmask(self, mask, value)View on GitHub (pinned to 71959b8cb9)
Solutions
- Use a slice or array key to place multiple values: arr[0:2] = ['a', 'b'].
- Pass a scalar value for a scalar key: arr[0] = 'a'.
- Check lib.is_scalar(value) and adjust the key accordingly.
Example fix
// before string_array[0] = ['a', 'b'] // after string_array[0:2] = ['a', 'b']
Defensive patterns
Strategy: validation
Validate before calling
import numpy as np
from pandas._libs import lib
if lib.is_scalar(key) and not lib.is_scalar(value):
key = slice(key, key + len(value)) if isinstance(value, (list, np.ndarray)) else key
string_array[key] = value Type guard
from pandas._libs import lib
def key_value_shapes_match(key, value) -> bool:
return lib.is_scalar(key) == lib.is_scalar(value) Prevention
- Pair scalar keys with scalar values, and slice/array keys with sequences.
- Use arr[i:j] = sequence to place multiple values.
- Validate that key and value scalar-ness agree before assignment.
When it happens
Trigger: Calling string_array[0] = ['a', 'b'], string_array[0] = np.array(['a','b']), or any assignment that puts a sequence into one scalar index.
Common situations: Accidentally passing a list where a single value is expected; off-by-one in slicing that collapses to a scalar key while the value stays list-like.
Related errors
- Lengths of operands do not match: {len(self)} != {len(other)
- Invalid value for dtype 'str'. Value should be a string or m
- Cannot modify read-only array
- too many dims to broadcast
- cannot broadcast result
AI-assisted analysis of pandas-dev/pandas@71959b8cb9 (2026-08-07).
Data as JSON: /api/errors/f71d5b7340c839fa.
Report an issue: GitHub.