{"record":{"id":"5b4a9cfd006f6ae8","repo":"pandas-dev/pandas","slug":"index-key-is-out-of-bounds-for-axis-0-with-size","errorCode":null,"errorMessage":"index {key} is out of bounds for axis 0 with size {n}","messagePattern":"index (.+?) is out of bounds for axis 0 with size (.+?)","errorType":"exception","errorClass":"IndexError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/arrow/array.py","lineNumber":2917,"sourceCode":"        if com.is_null_slice(key):\n            # fast path (GH50248)\n            if (\n                isinstance(value, (pa.Array, pa.ChunkedArray))\n                and value.type == self._pa_array.type\n                and len(value) == len(self)\n            ):\n                data = value\n            else:\n                data = self._if_else(True, value, self._pa_array)\n\n        elif is_integer(key):\n            # fast path\n            key = cast(\"int\", key)\n            n = len(self)\n            if key < 0:\n                key += n\n            if not 0 <= key < n:\n                raise IndexError(\n                    f\"index {key} is out of bounds for axis 0 with size {n}\"\n                )\n            if isinstance(value, pa.Scalar):\n                value = value.as_py()\n            elif is_list_like(value):\n                raise ValueError(\"Length of indexer and values mismatch\")\n            chunks = [\n                *self._pa_array[:key].chunks,\n                pa.array([value], type=self._pa_array.type, from_pandas=is_nan_na()),\n                *self._pa_array[key + 1 :].chunks,\n            ]\n            data = pa.chunked_array(chunks).combine_chunks()\n\n        elif is_bool_dtype(key):\n            key = np.asarray(key, dtype=np.bool_)\n            data = self._replace_with_mask(self._pa_array, key, value)\n\n        elif is_scalar(value) or isinstance(value, pa.Scalar):","sourceCodeStart":2899,"sourceCodeEnd":2935,"githubUrl":"https://github.com/pandas-dev/pandas/blob/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/arrays/arrow/array.py#L2899-L2935","documentation":"In __setitem__'s integer-key fast path, after normalizing negative indices (key += n) the code checks 0 <= key < n. If the resolved index falls outside the array length, it raises IndexError with the standard numpy-style message naming axis 0 and the size. This matches ndarray.__setitem__ semantics.","triggerScenarios":"Assigning to a single position with an out-of-range integer index on a pyarrow-backed Series/array, e.g. s.iloc[10] = x where len(s) <= 10.","commonSituations":"Loop indices computed without bounds check; off-by-one after filtering; assigning into an array sized against stale metadata.","solutions":["Validate 0 <= key < len(arr) (or -len(arr) <= key < 0) before assignment.","Resize the structure (append/reindex) instead of writing past the end.","Re-derive the index after any operation that changes array length."],"exampleFix":"// before\ns = pd.Series([1, 2, 3], dtype=\"int64[pyarrow]\")\ns.iloc[5] = 99\n// after\ns = pd.Series([1, 2, 3], dtype=\"int64[pyarrow]\")\nif 0 <= 5 < len(s):\n    s.iloc[5] = 99","handlingStrategy":"validation","validationCode":"def safe_pos_setitem(arr, key, value):\n    n = len(arr)\n    if key < 0:\n        key += n\n    if not 0 <= key < n:\n        raise IndexError(f\"index {key} out of range [0,{n})\")\n    arr[key] = value","typeGuard":"def index_in_range(arr, key) -> bool:\n    n = len(arr)\n    k = key + n if key < 0 else key\n    return 0 <= k < n","tryCatchPattern":"try:\n    s.iloc[i] = v\nexcept IndexError:\n    # resize or reindex, then retry\n    ...","preventionTips":["Bounds-check integer keys before iloc assignment.","Re-derive indices after filtering."],"tags":["pyarrow","setitem","out-of-bounds","indexerror"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}