TheAlgorithms/Python · error · ValueError

Cannot multiply matrix of dimensions ({rows[0]},{cols[0]}) a

Error message

Cannot multiply matrix of dimensions ({rows[0]},{cols[0]}) and ({rows[1]},{cols[1]})

What it means

Raised by multiply() in matrix_operation when matrix_a's column count does not equal matrix_b's row count — the inner-dimension rule of matrix multiplication. The message helpfully reports both dimensions as (rows, cols) pairs. Beware: if either argument fails _check_not_integer, rows/cols are never assigned and you get an UnboundLocalError instead, so this ValueError implies both operands were well-formed matrices.

Source

Thrown at matrix/matrix_operation.py:77

def multiply(matrix_a: list[list[int]], matrix_b: list[list[int]]) -> list[list[int]]:
    """
    >>> multiply([[1,2],[3,4]],[[5,5],[7,5]])
    [[19, 15], [43, 35]]
    >>> multiply([[1,2.5],[3,4.5]],[[5,5],[7,5]])
    [[22.5, 17.5], [46.5, 37.5]]
    >>> multiply([[1, 2, 3]], [[2], [3], [4]])
    [[20]]
    """
    if _check_not_integer(matrix_a) and _check_not_integer(matrix_b):
        rows, cols = _verify_matrix_sizes(matrix_a, matrix_b)

    if cols[0] != rows[1]:
        msg = (
            "Cannot multiply matrix of dimensions "
            f"({rows[0]},{cols[0]}) and ({rows[1]},{cols[1]})"
        )
        raise ValueError(msg)
    return [
        [sum(m * n for m, n in zip(i, j)) for j in zip(*matrix_b)] for i in matrix_a
    ]


def identity(n: int) -> list[list[int]]:
    """
    :param n: dimension for nxn matrix
    :type n: int
    :return: Identity matrix of shape [n, n]
    >>> identity(3)
    [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
    """
    n = int(n)
    return [[int(row == column) for column in range(n)] for row in range(n)]


def transpose(

View on GitHub (pinned to f5988cc097)

Solutions

  1. Print the shapes first: print(len(a), len(a[0]), len(b), len(b[0])) and confirm len(a[0]) == len(b).
  2. Transpose matrix_b if the data is oriented the other way: b = list(map(list, zip(*b))).
  3. Swap operands if the math allows (B @ A vs A @ B).
  4. Validate at the data-ingestion step so malformed matrices never reach multiply().

Example fix

# before
result = multiply([[1, 2, 3]], [[1, 2], [3, 4]])  # 1x3 * 2x2 -> ValueError

# after
result = multiply([[1, 2, 3]], [[1], [2], [3]])  # 1x3 * 3x1 -> [[14]]
Defensive patterns

Strategy: validation

Validate before calling

def shape(m):
    return len(m), len(m[0]) if m else (0, 0)

ra, ca = shape(matrix_a)
rb, cb = shape(matrix_b)
if ca != rb:
    raise ValueError(f"inner dimensions differ: {ra}x{ca} times {rb}x{cb}")
result = multiply(matrix_a, matrix_b)

Type guard

def are_mul_compatible(a: list, b: list) -> bool:
    """Guard: both 2-D nested lists with cols(a) == rows(b)."""
    return (
        isinstance(a, list) and isinstance(b, list)
        and bool(a) and bool(b)
        and isinstance(a[0], list) and isinstance(b[0], list)
        and len(a[0]) == len(b)
    )

Try / catch

try:
    result = multiply(a, b)
except ValueError as e:
    if "Cannot multiply" in str(e):
        b = list(map(list, zip(*b)))  # try transposed orientation
        result = multiply(a, b)
    else:
        raise

Prevention

When it happens

Trigger: multiply([[1, 2, 3]], [[1, 2]]) (1x3 times 2x2), or any A (m x n) times B (p x q) with n != p. Transposing the wrong operand is the classic trigger.

Common situations: Dot product of a row vector and column vector stored with matching outer shapes; mixing up operand order relative to NumPy conventions; batches of matrices where one item has a stray column.

Related errors


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