{"record":{"id":"e88bc64ce280cfbf","repo":"TheAlgorithms/Python","slug":"index-out-of-range","errorCode":null,"errorMessage":"index out of range","messagePattern":"index out of range","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"data_structures/arrays/index_2d_array_in_1d.py","lineNumber":97,"sourceCode":"        ...\n    ValueError: index out of range\n    >>> index_2d_array_in_1d([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]], 12)\n    Traceback (most recent call last):\n        ...\n    ValueError: index out of range\n    >>> index_2d_array_in_1d([[]], 0)\n    Traceback (most recent call last):\n        ...\n    ValueError: no items in array\n    \"\"\"\n    rows = len(array)\n    cols = len(array[0])\n\n    if rows == 0 or cols == 0:\n        raise ValueError(\"no items in array\")\n\n    if index < 0 or index >= rows * cols:\n        raise ValueError(\"index out of range\")\n\n    return array[index // cols][index % cols]\n\n\nif __name__ == \"__main__\":\n    import doctest\n\n    doctest.testmod()\n","sourceCodeStart":79,"sourceCodeEnd":106,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/data_structures/arrays/index_2d_array_in_1d.py#L79-L106","documentation":"Raised by index_2d_array_in_1d() in data_structures/arrays/index_2d_array_in_1d.py when the flat index is negative or >= rows * cols. The function validates the linear index against the total element count before computing array[index // cols][index % cols], so this fires only when the array itself is non-empty.","triggerScenarios":"Calling index_2d_array_in_1d([[1,2],[3,4]], -1) or index_2d_array_in_1d([[1,2],[3,4]], 4) (max valid is 3). Also triggered by non-integer-like indexes after failed implicit coercion assumptions.","commonSituations":"Off-by-one loops (range(rows*cols + 1)), flat indexes computed from ragged/irregular 2D lists where len(array[0])*rows overestimates or underestimates actual counts, or passing a 1-based index to a 0-based API.","solutions":["Clamp/validate before calling: 0 <= index < len(array) * len(array[0]).","Check loop bounds: use range(rows * cols), not +1; remember indexes are 0-based.","If the 2D list is ragged (rows of different lengths), normalize it first — the cols = len(array[0]) math assumes rectangular data."],"exampleFix":"# before\nfor i in range(rows * cols + 1):\n    val = index_2d_array_in_1d(grid, i)  # last i is out of range\n\n# after\nfor i in range(rows * cols):\n    val = index_2d_array_in_1d(grid, i)","handlingStrategy":"validation","validationCode":"rows, cols = len(array), len(array[0])\nif not 0 <= index < rows * cols:\n    raise IndexError(f'{index} outside 0..{rows*cols-1}')\nval = index_2d_array_in_1d(array, index)","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Use range(rows * cols) in loops — indexes are 0-based","Normalize ragged 2D lists before flat indexing"],"tags":["value-validation","array","index","off-by-one"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}