TheAlgorithms/Python · error · ValueError

Only square matrices can be raised to a power

Error message

Only square matrices can be raised to a power

What it means

Raised by Matrix.__pow__ when the base matrix is not square. Matrix powers (positive via repeated multiplication, zero via identity, negative via inverse) are only defined for n x n matrices, so the method checks self.is_square before anything else. A non-square matrix has no power for any exponent, including 0 in this implementation's contract.

Source

Thrown at matrix/matrix_class.py:344

                    "The number of columns in the first matrix must "
                    "be equal to the number of rows in the second"
                )
            return Matrix(
                [
                    [Matrix.dot_product(row, column) for column in other.columns()]
                    for row in self.rows
                ]
            )
        else:
            raise TypeError(
                "A Matrix can only be multiplied by an int, float, or another matrix"
            )

    def __pow__(self, other: int) -> Matrix:
        if not isinstance(other, int):
            raise TypeError("A Matrix can only be raised to the power of an int")
        if not self.is_square:
            raise ValueError("Only square matrices can be raised to a power")
        if other == 0:
            return self.identity()
        if other < 0:
            if self.is_invertable():
                return self.inverse() ** (-other)
            raise ValueError(
                "Only invertable matrices can be raised to a negative power"
            )
        result = self
        for _ in range(other - 1):
            result *= self
        return result

    @classmethod
    def dot_product(cls, row: list[int], column: list[int]) -> int:
        return sum(row[i] * column[i] for i in range(len(row)))

View on GitHub (pinned to f5988cc097)

Solutions

  1. Inspect the matrix dimensions (num_rows vs num_columns) and fix the upstream construction so the matrix is square.
  2. If you meant to multiply by itself a rectangular layout, reconsider the operation: compute A * A.transpose() or use a different algebraic formulation.
  3. If a square transition/weight matrix was intended, check for a dropped row/column when parsing input data (e.g. a header line skipped incorrectly).
  4. Unit-test matrix construction with an is_square assertion before powering.

Example fix

# before
m = Matrix([[1, 2, 3], [4, 5, 6]])
result = m ** 2  # ValueError: not square

# after
square = m * m.transpose()  # 2x3 * 3x2 -> 2x2, now powerable
result = square ** 2
Defensive patterns

Strategy: validation

Validate before calling

if not matrix.is_square:
    raise ValueError(
        f"matrix is {matrix.num_rows}x{matrix.num_columns}; powers need a square matrix"
    )
result = matrix ** k

Type guard

def is_square_matrix(m: Matrix) -> bool:
    """Guard: object is a Matrix with equal row/column counts."""
    return isinstance(m, Matrix) and m.num_rows == m.num_columns

Try / catch

try:
    result = matrix ** k
except ValueError as e:
    if "square" in str(e):
        # restate the actual shape for easier debugging
        raise ValueError(f"non-square {matrix.num_rows}x{matrix.num_columns} matrix") from e
    raise

Prevention

When it happens

Trigger: Calling matrix ** k on any m x n matrix where m != n, e.g. a 2x3 Matrix raised to power 2, or a row-vector Matrix raised to power 0. The check fires before the exponent sign is even examined.

Common situations: Applying transformation matrices to data matrices (e.g. raising a data matrix instead of the covariance/transition matrix to a power); assuming A**0 returns something for rectangular matrices; graph adjacency matrices built with a bug that drops a row.

Related errors


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