TheAlgorithms/Python · error · ValueError

operands could not be broadcast together with shape ({shape[

Error message

operands could not be broadcast together with shape ({shape[0], shape[1]}), ({shape[2], shape[3]})

What it means

Raised by _verify_matrix_sizes when two matrices do not have identical shapes. Despite the NumPy-flavored wording, this helper does not broadcast — it requires exact equality: shape[0] == shape[3] and shape[1] == shape[2] means rows_a == cols_b and cols_a == rows_b for add/subtract-style element-wise ops, effectively same-shape matrices. It is invoked by add(), subtract(), and multiply() to validate operands.

Source

Thrown at matrix/matrix_operation.py:182

def _check_not_integer(matrix: list[list[int]]) -> bool:
    return not isinstance(matrix, int) and not isinstance(matrix[0], int)


def _shape(matrix: list[list[int]]) -> tuple[int, int]:
    return len(matrix), len(matrix[0])


def _verify_matrix_sizes(
    matrix_a: list[list[int]], matrix_b: list[list[int]]
) -> tuple[tuple[int, int], tuple[int, int]]:
    shape = _shape(matrix_a) + _shape(matrix_b)
    if shape[0] != shape[3] or shape[1] != shape[2]:
        msg = (
            "operands could not be broadcast together with shape "
            f"({shape[0], shape[1]}), ({shape[2], shape[3]})"
        )
        raise ValueError(msg)
    return (shape[0], shape[2]), (shape[1], shape[3])


def main() -> None:
    matrix_a = [[12, 10], [3, 9]]
    matrix_b = [[3, 4], [7, 4]]
    matrix_c = [[11, 12, 13, 14], [21, 22, 23, 24], [31, 32, 33, 34], [41, 42, 43, 44]]
    matrix_d = [[3, 0, 2], [2, 0, -2], [0, 1, 1]]
    print(f"Add Operation, {add(matrix_a, matrix_b) = } \n")
    print(f"Multiply Operation, {multiply(matrix_a, matrix_b) = } \n")
    print(f"Identity: {identity(5)}\n")
    print(f"Minor of {matrix_c} = {minor(matrix_c, 1, 2)} \n")
    print(f"Determinant of {matrix_b} = {determinant(matrix_b)} \n")
    print(f"Inverse of {matrix_d} = {inverse(matrix_d)}\n")


if __name__ == "__main__":
    import doctest

View on GitHub (pinned to f5988cc097)

Solutions

  1. Make the shapes identical before calling add/subtract: pad, trim, or reshape the data upstream.
  2. If you expected NumPy broadcasting, switch to NumPy arrays and np.add / + which broadcast properly.
  3. Replicate the missing elements explicitly (e.g. tile the smaller matrix) to reach equal shapes.
  4. Add an early assert len(a) == len(b) and len(a[0]) == len(b[0]) with a clearer message at your call site.

Example fix

# before
result = add([[1], [2]], [[1, 2], [3, 4]])  # ValueError (no broadcasting)

# after
import numpy as np
result = (np.array([[1], [2]]) + np.array([[1, 2], [3, 4]])).tolist()  # broadcasts -> [[2, 3], [5, 6]]
Defensive patterns

Strategy: validation

Validate before calling

def same_shape(a, b) -> bool:
    return len(a) == len(b) and all(len(ra) == len(rb) for ra, rb in zip(a, b))

if not same_shape(matrix_a, matrix_b):
    raise ValueError(f"shapes differ: {len(a)}x{len(a[0])} vs {len(b)}x{len(b[0])}")
result = add(matrix_a, matrix_b)

Type guard

def are_same_shape_matrices(a: list, b: list) -> bool:
    """Guard: both 2-D nested lists with identical row counts and row lengths."""
    return (
        isinstance(a, list) and isinstance(b, list)
        and len(a) == len(b)
        and all(isinstance(ra, list) and isinstance(rb, list) and len(ra) == len(rb)
                for ra, rb in zip(a, b))
    )

Try / catch

try:
    result = add(a, b)
except ValueError as e:
    if "broadcast" in str(e):
        raise ValueError("no broadcasting here; make shapes equal first") from e
    raise

Prevention

When it happens

Trigger: add([[1, 2]], [[1, 2], [3, 4]]) (1x2 plus 2x2), or subtract of a 2x3 and 3x2 matrix. For multiply(), note the returned tuple is rearranged ((rows_a, cols_b-style pairs)), so any shape mismatch in element-wise context surfaces with this broadcast-style message.

Common situations: Coming from NumPy where broadcasting makes (2,1) + (2,2) legal; concatenating batches with inconsistent row counts; comparing data matrices after a reshape step that only touched one side.

Related errors


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