{"record":{"id":"9fdb790ce2d0f123","repo":"TheAlgorithms/Python","slug":"cannot-multiply-matrix-of-dimensions-rows-0-c","errorCode":null,"errorMessage":"Cannot multiply matrix of dimensions ({rows[0]},{cols[0]}) and ({rows[1]},{cols[1]})","messagePattern":"Cannot multiply matrix of dimensions \\((.+?),(.+?)\\) and \\((.+?),(.+?)\\)","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"matrix/matrix_operation.py","lineNumber":77,"sourceCode":"\ndef multiply(matrix_a: list[list[int]], matrix_b: list[list[int]]) -> list[list[int]]:\n    \"\"\"\n    >>> multiply([[1,2],[3,4]],[[5,5],[7,5]])\n    [[19, 15], [43, 35]]\n    >>> multiply([[1,2.5],[3,4.5]],[[5,5],[7,5]])\n    [[22.5, 17.5], [46.5, 37.5]]\n    >>> multiply([[1, 2, 3]], [[2], [3], [4]])\n    [[20]]\n    \"\"\"\n    if _check_not_integer(matrix_a) and _check_not_integer(matrix_b):\n        rows, cols = _verify_matrix_sizes(matrix_a, matrix_b)\n\n    if cols[0] != rows[1]:\n        msg = (\n            \"Cannot multiply matrix of dimensions \"\n            f\"({rows[0]},{cols[0]}) and ({rows[1]},{cols[1]})\"\n        )\n        raise ValueError(msg)\n    return [\n        [sum(m * n for m, n in zip(i, j)) for j in zip(*matrix_b)] for i in matrix_a\n    ]\n\n\ndef identity(n: int) -> list[list[int]]:\n    \"\"\"\n    :param n: dimension for nxn matrix\n    :type n: int\n    :return: Identity matrix of shape [n, n]\n    >>> identity(3)\n    [[1, 0, 0], [0, 1, 0], [0, 0, 1]]\n    \"\"\"\n    n = int(n)\n    return [[int(row == column) for column in range(n)] for row in range(n)]\n\n\ndef transpose(","sourceCodeStart":59,"sourceCodeEnd":95,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/matrix/matrix_operation.py#L59-L95","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Print the shapes first: print(len(a), len(a[0]), len(b), len(b[0])) and confirm len(a[0]) == len(b).","Transpose matrix_b if the data is oriented the other way: b = list(map(list, zip(*b))).","Swap operands if the math allows (B @ A vs A @ B).","Validate at the data-ingestion step so malformed matrices never reach multiply()."],"exampleFix":"# before\nresult = multiply([[1, 2, 3]], [[1, 2], [3, 4]])  # 1x3 * 2x2 -> ValueError\n\n# after\nresult = multiply([[1, 2, 3]], [[1], [2], [3]])  # 1x3 * 3x1 -> [[14]]","handlingStrategy":"validation","validationCode":"def shape(m):\n    return len(m), len(m[0]) if m else (0, 0)\n\nra, ca = shape(matrix_a)\nrb, cb = shape(matrix_b)\nif ca != rb:\n    raise ValueError(f\"inner dimensions differ: {ra}x{ca} times {rb}x{cb}\")\nresult = multiply(matrix_a, matrix_b)","typeGuard":"def are_mul_compatible(a: list, b: list) -> bool:\n    \"\"\"Guard: both 2-D nested lists with cols(a) == rows(b).\"\"\"\n    return (\n        isinstance(a, list) and isinstance(b, list)\n        and bool(a) and bool(b)\n        and isinstance(a[0], list) and isinstance(b[0], list)\n        and len(a[0]) == len(b)\n    )","tryCatchPattern":"try:\n    result = multiply(a, b)\nexcept ValueError as e:\n    if \"Cannot multiply\" in str(e):\n        b = list(map(list, zip(*b)))  # try transposed orientation\n        result = multiply(a, b)\n    else:\n        raise","preventionTips":["Log (rows, cols) of both operands when assembling multiplication pipelines.","Remember that non-matrix operands to multiply() cause an UnboundLocalError, not this clean ValueError — validate shapes first.","Encapsulate shape checks in a helper used by all call sites rather than inline conditionals."],"tags":["matrix","dimension-mismatch","valueerror","linear-algebra"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}