{"record":{"id":"f71d5b7340c839fa","repo":"pandas-dev/pandas","slug":"setting-an-array-element-with-a-sequence","errorCode":null,"errorMessage":"setting an array element with a sequence.","messagePattern":"setting an array element with a sequence\\.","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/string_.py","lineNumber":879,"sourceCode":"                value = np.asarray(value)\n            if len(value) and not lib.is_string_array(value, skipna=True):\n                raise TypeError(\n                    \"Invalid value for dtype 'str'. Value should be a \"\n                    \"string or missing value (or array of those).\"\n                )\n        return value\n\n    def __setitem__(self, key, value) -> None:\n        if self._readonly:\n            raise ValueError(\"Cannot modify read-only array\")\n\n        value = self._validate_setitem_value(value)\n\n        key = check_array_indexer(self, key)\n        scalar_key = lib.is_scalar(key)\n        scalar_value = lib.is_scalar(value)\n        if scalar_key and not scalar_value:\n            raise ValueError(\"setting an array element with a sequence.\")\n\n        if not scalar_value:\n            if value.dtype == self.dtype:\n                value = value._ndarray\n            else:\n                value = np.asarray(value)\n                mask = isna(value)\n                if mask.any():\n                    value = value.copy()\n                    value[isna(value)] = self.dtype.na_value\n\n        super().__setitem__(key, value)\n\n    def _putmask(self, mask: npt.NDArray[np.bool_], value) -> None:\n        # the super() method NDArrayBackedExtensionArray._putmask uses\n        # np.putmask which doesn't properly handle None/pd.NA, so using the\n        # base class implementation that uses __setitem__\n        ExtensionArray._putmask(self, mask, value)","sourceCodeStart":861,"sourceCodeEnd":897,"githubUrl":"https://github.com/pandas-dev/pandas/blob/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/arrays/string_.py#L861-L897","documentation":"StringArray.__setitem__ rejects the case where a scalar index key targets a single slot but the supplied value is a non-scalar sequence (e.g. a list or array). pandas enforces single-position assignment stays single-valued to avoid silently nesting sequences inside object-backed string storage, which would corrupt the array's invariant that each element is a Python str or NA.","triggerScenarios":"Assigning a list/tuple/np.ndarray to a single integer position of a StringArray or string-dtyped Series: `s.iloc[0] = ['a','b']` or `arr[3] = np.array(['x'])`. Triggered inside __setitem__ when lib.is_scalar(key) is True but lib.is_scalar(value) is False after _validate_setitem_value.","commonSituations":"Loop-driven assignment that builds a list per iteration and writes it into one cell; a broadcast mistake where df.loc[i, 'col'] = some_list; switching dtype from object to 'string' and hitting the newly-enforced scalar invariant.","solutions":["Assign a scalar string or NA when indexing a single position: s.iloc[0] = 'a'.","If you intend to set multiple cells, use a matching-length boolean or slice key: s.iloc[[0,1]] = ['a','b'].","If the value is a one-element array, extract the scalar first: s.iloc[i] = arr[0].","If you must store sequences per row, keep the column dtype as object instead of 'string'."],"exampleFix":"// before\ns = pd.Series(['x','y'], dtype='string')\ns.iloc[0] = ['a','b']  # ValueError\n// after\ns.iloc[[0,1]] = ['a','b']  # set multiple cells\n# or for a single cell\ns.iloc[0] = 'a'","handlingStrategy":"validation","validationCode":"from pandas.core.dtypes.common import is_scalar\ndef assign_single_string_cell(arr, i, value):\n    if not is_scalar(value):\n        raise ValueError(f\"Refusing to assign non-scalar to single cell {i}; use a slice/boolean key for arrays.\")\n    arr[i] = value","typeGuard":"def is_assignable_to_single_cell(value) -> bool:\n    from pandas.api.types import is_scalar\n    return is_scalar(value)","tryCatchPattern":"try:\n    s.iloc[i] = value\nexcept ValueError as e:\n    if 'setting an array element with a sequence' in str(e):\n        s.iloc[[i, *extra]] = value  # or use scalar\n    else:\n        raise","preventionTips":["Always pass scalars to single-position assignment on string-dtype arrays.","Reserve list/array assignment for boolean or slice keys of matching length.","Keep dtype as object if you must store sequences per row."],"tags":["pandas","string-array","setitem","dtype","assignment"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}