{"record":{"id":"4a16f8b239797f0c","repo":"TheAlgorithms/Python","slug":"indices-out-of-bounds","errorCode":null,"errorMessage":"Indices out of bounds","messagePattern":"Indices out of bounds","errorType":"exception","errorClass":"Exception","httpStatus":null,"severity":"error","filePath":"linear_algebra/src/lib.py","lineNumber":403,"sourceCode":"        returns the minor along (x, y)\n        \"\"\"\n        if self.__height != self.__width:\n            raise Exception(\"Matrix is not square\")\n        minor = self.__matrix[:x] + self.__matrix[x + 1 :]\n        for i in range(len(minor)):\n            minor[i] = minor[i][:y] + minor[i][y + 1 :]\n        return Matrix(minor, self.__width - 1, self.__height - 1).determinant()\n\n    def cofactor(self, x: int, y: int) -> float:\n        \"\"\"\n        returns the cofactor (signed minor) along (x, y)\n        \"\"\"\n        if self.__height != self.__width:\n            raise Exception(\"Matrix is not square\")\n        if 0 <= x < self.__height and 0 <= y < self.__width:\n            return (-1) ** (x + y) * self.minor(x, y)\n        else:\n            raise Exception(\"Indices out of bounds\")\n\n    def determinant(self) -> float:\n        \"\"\"\n        returns the determinant of an nxn matrix using Laplace expansion\n        \"\"\"\n        if self.__height != self.__width:\n            raise Exception(\"Matrix is not square\")\n        if self.__height < 1:\n            raise Exception(\"Matrix has no element\")\n        elif self.__height == 1:\n            return self.__matrix[0][0]\n        elif self.__height == 2:\n            return (\n                self.__matrix[0][0] * self.__matrix[1][1]\n                - self.__matrix[0][1] * self.__matrix[1][0]\n            )\n        else:\n            cofactor_prods = [","sourceCodeStart":385,"sourceCodeEnd":421,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/linear_algebra/src/lib.py#L385-L421","documentation":"Raised by Matrix.cofactor(x, y) in linear_algebra/src/lib.py:403 when (x, y) falls outside 0 <= x < height and 0 <= y < width (checked after the squareness guard). The cofactor signs and the minor construction need a valid row/column pair, so out-of-range indices — including negative indices, which this API does not accept — raise a bare Exception.","triggerScenarios":"Calling m.cofactor(3, 0) on a 3x3 matrix (valid range is 0..2), using 1-based loop bounds like range(1, n + 1), or negative indices copied from Python list idioms.","commonSituations":"Laplace expansion loops with inclusive bounds, converting 1-based textbook formulas, or indices derived from enumerate() starting at 1.","solutions":["Bounds-check 0 <= x < m.height() and 0 <= y < m.width() before calling.","Use range(n) with n = m.height() in expansion loops.","Convert 1-based external coordinates to 0-based.","Catch Exception narrowly to add context (which x, y failed)."],"exampleFix":"// before\nfor x in range(1, n + 1):\n    acc += row[x - 1] * m.cofactor(0, x)  # Exception at x == n\n\n// after\nfor y in range(m.width()):\n    acc += m.component(0, y) * m.cofactor(0, y)","handlingStrategy":"validation","validationCode":"if not (0 <= x < m.height() and 0 <= y < m.width()):\n    raise IndexError(f\"({x}, {y}) outside {m.height()}x{m.width()}\")\nvalue = m.cofactor(x, y)","typeGuard":"def is_valid_cell(m, x, y) -> bool:\n    return isinstance(x, int) and isinstance(y, int) and 0 <= x < m.height() and 0 <= y < m.width()","tryCatchPattern":"try:\n    value = m.cofactor(x, y)\nexcept Exception as e:\n    if \"Indices out of bounds\" in str(e):\n        raise IndexError(f\"cofactor cell ({x},{y}) invalid for {m.height()}x{m.width()}\") from e\n    raise","preventionTips":["Use range(n) (0-based, half-open) in expansion loops; range(1, n+1) with direct indexing is the classic trigger.","This API rejects negative indices — convert Python-style negatives before calling.","Distinguish the two cofactor errors by message: 'Matrix is not square' (shape) vs 'Indices out of bounds' (position).","Validate (x, y) once per loop iteration or hoist a bounds check before the loop."],"tags":["linear-algebra","matrix","cofactor","index-out-of-range","off-by-one"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}