TheAlgorithms/Python · error · Exception

Indices out of bounds

Error message

Indices out of bounds

What it means

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.

Source

Thrown at linear_algebra/src/lib.py:403

        returns the minor along (x, y)
        """
        if self.__height != self.__width:
            raise Exception("Matrix is not square")
        minor = self.__matrix[:x] + self.__matrix[x + 1 :]
        for i in range(len(minor)):
            minor[i] = minor[i][:y] + minor[i][y + 1 :]
        return Matrix(minor, self.__width - 1, self.__height - 1).determinant()

    def cofactor(self, x: int, y: int) -> float:
        """
        returns the cofactor (signed minor) along (x, y)
        """
        if self.__height != self.__width:
            raise Exception("Matrix is not square")
        if 0 <= x < self.__height and 0 <= y < self.__width:
            return (-1) ** (x + y) * self.minor(x, y)
        else:
            raise Exception("Indices out of bounds")

    def determinant(self) -> float:
        """
        returns the determinant of an nxn matrix using Laplace expansion
        """
        if self.__height != self.__width:
            raise Exception("Matrix is not square")
        if self.__height < 1:
            raise Exception("Matrix has no element")
        elif self.__height == 1:
            return self.__matrix[0][0]
        elif self.__height == 2:
            return (
                self.__matrix[0][0] * self.__matrix[1][1]
                - self.__matrix[0][1] * self.__matrix[1][0]
            )
        else:
            cofactor_prods = [

View on GitHub (pinned to f5988cc097)

Solutions

  1. Bounds-check 0 <= x < m.height() and 0 <= y < m.width() before calling.
  2. Use range(n) with n = m.height() in expansion loops.
  3. Convert 1-based external coordinates to 0-based.
  4. Catch Exception narrowly to add context (which x, y failed).

Example fix

// before
for x in range(1, n + 1):
    acc += row[x - 1] * m.cofactor(0, x)  # Exception at x == n

// after
for y in range(m.width()):
    acc += m.component(0, y) * m.cofactor(0, y)
Defensive patterns

Strategy: validation

Validate before calling

if not (0 <= x < m.height() and 0 <= y < m.width()):
    raise IndexError(f"({x}, {y}) outside {m.height()}x{m.width()}")
value = m.cofactor(x, y)

Type guard

def is_valid_cell(m, x, y) -> bool:
    return isinstance(x, int) and isinstance(y, int) and 0 <= x < m.height() and 0 <= y < m.width()

Try / catch

try:
    value = m.cofactor(x, y)
except Exception as e:
    if "Indices out of bounds" in str(e):
        raise IndexError(f"cofactor cell ({x},{y}) invalid for {m.height()}x{m.width()}") from e
    raise

Prevention

When it happens

Trigger: 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.

Common situations: Laplace expansion loops with inclusive bounds, converting 1-based textbook formulas, or indices derived from enumerate() starting at 1.

Related errors


AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14). Data as JSON: /api/errors/4a16f8b239797f0c. Report an issue: GitHub.