{"record":{"id":"0c54aad10b78c860","repo":"TheAlgorithms/Python","slug":"operands-could-not-be-broadcast-together-with-shap","errorCode":null,"errorMessage":"operands could not be broadcast together with shape ({shape[0], shape[1]}), ({shape[2], shape[3]})","messagePattern":"operands could not be broadcast together with shape \\((.+?)\\), \\((.+?)\\)","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"matrix/matrix_operation.py","lineNumber":182,"sourceCode":"\ndef _check_not_integer(matrix: list[list[int]]) -> bool:\n    return not isinstance(matrix, int) and not isinstance(matrix[0], int)\n\n\ndef _shape(matrix: list[list[int]]) -> tuple[int, int]:\n    return len(matrix), len(matrix[0])\n\n\ndef _verify_matrix_sizes(\n    matrix_a: list[list[int]], matrix_b: list[list[int]]\n) -> tuple[tuple[int, int], tuple[int, int]]:\n    shape = _shape(matrix_a) + _shape(matrix_b)\n    if shape[0] != shape[3] or shape[1] != shape[2]:\n        msg = (\n            \"operands could not be broadcast together with shape \"\n            f\"({shape[0], shape[1]}), ({shape[2], shape[3]})\"\n        )\n        raise ValueError(msg)\n    return (shape[0], shape[2]), (shape[1], shape[3])\n\n\ndef main() -> None:\n    matrix_a = [[12, 10], [3, 9]]\n    matrix_b = [[3, 4], [7, 4]]\n    matrix_c = [[11, 12, 13, 14], [21, 22, 23, 24], [31, 32, 33, 34], [41, 42, 43, 44]]\n    matrix_d = [[3, 0, 2], [2, 0, -2], [0, 1, 1]]\n    print(f\"Add Operation, {add(matrix_a, matrix_b) = } \\n\")\n    print(f\"Multiply Operation, {multiply(matrix_a, matrix_b) = } \\n\")\n    print(f\"Identity: {identity(5)}\\n\")\n    print(f\"Minor of {matrix_c} = {minor(matrix_c, 1, 2)} \\n\")\n    print(f\"Determinant of {matrix_b} = {determinant(matrix_b)} \\n\")\n    print(f\"Inverse of {matrix_d} = {inverse(matrix_d)}\\n\")\n\n\nif __name__ == \"__main__\":\n    import doctest","sourceCodeStart":164,"sourceCodeEnd":200,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/matrix/matrix_operation.py#L164-L200","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Make the shapes identical before calling add/subtract: pad, trim, or reshape the data upstream.","If you expected NumPy broadcasting, switch to NumPy arrays and np.add / + which broadcast properly.","Replicate the missing elements explicitly (e.g. tile the smaller matrix) to reach equal shapes.","Add an early assert len(a) == len(b) and len(a[0]) == len(b[0]) with a clearer message at your call site."],"exampleFix":"# before\nresult = add([[1], [2]], [[1, 2], [3, 4]])  # ValueError (no broadcasting)\n\n# after\nimport numpy as np\nresult = (np.array([[1], [2]]) + np.array([[1, 2], [3, 4]])).tolist()  # broadcasts -> [[2, 3], [5, 6]]","handlingStrategy":"validation","validationCode":"def same_shape(a, b) -> bool:\n    return len(a) == len(b) and all(len(ra) == len(rb) for ra, rb in zip(a, b))\n\nif not same_shape(matrix_a, matrix_b):\n    raise ValueError(f\"shapes differ: {len(a)}x{len(a[0])} vs {len(b)}x{len(b[0])}\")\nresult = add(matrix_a, matrix_b)","typeGuard":"def are_same_shape_matrices(a: list, b: list) -> bool:\n    \"\"\"Guard: both 2-D nested lists with identical row counts and row lengths.\"\"\"\n    return (\n        isinstance(a, list) and isinstance(b, list)\n        and len(a) == len(b)\n        and all(isinstance(ra, list) and isinstance(rb, list) and len(ra) == len(rb)\n                for ra, rb in zip(a, b))\n    )","tryCatchPattern":"try:\n    result = add(a, b)\nexcept ValueError as e:\n    if \"broadcast\" in str(e):\n        raise ValueError(\"no broadcasting here; make shapes equal first\") from e\n    raise","preventionTips":["This library never broadcasts — do not port NumPy expressions expecting (n,1)+(n,m) to work.","Make shapes equal upstream: pad, trim, or tile the smaller matrix explicitly.","Switch to NumPy for the element-wise step if broadcasting semantics are actually wanted."],"tags":["matrix","shape-mismatch","broadcasting","valueerror"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}