{"record":{"id":"1b0dd0cec442169f","repo":"TheAlgorithms/Python","slug":"the-number-of-columns-in-the-first-matrix-must-be","errorCode":null,"errorMessage":"The number of columns in the first matrix must be equal to the number of rows in the second","messagePattern":"The number of columns in the first matrix must be equal to the number of rows in the second","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"matrix/matrix_class.py","lineNumber":325,"sourceCode":"\n    def __sub__(self, other: Matrix) -> Matrix:\n        if self.order != other.order:\n            raise ValueError(\"Subtraction requires matrices of the same order\")\n        return Matrix(\n            [\n                [self.rows[i][j] - other.rows[i][j] for j in range(self.num_columns)]\n                for i in range(self.num_rows)\n            ]\n        )\n\n    def __mul__(self, other: Matrix | float) -> Matrix:\n        if isinstance(other, (int, float)):\n            return Matrix(\n                [[int(element * other) for element in row] for row in self.rows]\n            )\n        elif isinstance(other, Matrix):\n            if self.num_columns != other.num_rows:\n                raise ValueError(\n                    \"The number of columns in the first matrix must \"\n                    \"be equal to the number of rows in the second\"\n                )\n            return Matrix(\n                [\n                    [Matrix.dot_product(row, column) for column in other.columns()]\n                    for row in self.rows\n                ]\n            )\n        else:\n            raise TypeError(\n                \"A Matrix can only be multiplied by an int, float, or another matrix\"\n            )\n\n    def __pow__(self, other: int) -> Matrix:\n        if not isinstance(other, int):\n            raise TypeError(\"A Matrix can only be raised to the power of an int\")\n        if not self.is_square:","sourceCodeStart":307,"sourceCodeEnd":343,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/matrix/matrix_class.py#L307-L343","documentation":"Raised by Matrix.__mul__ when performing matrix multiplication between two Matrix objects whose inner dimensions do not match: the left operand's column count must equal the right operand's row count. This is the standard algebraic constraint of matrix multiplication (an m x n matrix can only multiply an n x p matrix). The check happens before any dot products are computed, so no partial result is produced.","triggerScenarios":"Calling matrix_a * matrix_b where matrix_a.num_columns != matrix_b.num_rows, e.g. a 2x3 Matrix times a 2x2 Matrix. Scalar multiplication (int/float operand) never triggers this; only Matrix * Matrix with mismatched inner dimensions does.","commonSituations":"Transposing data for a linear-algebra pipeline and forgetting the order of operands; multiplying a row vector by a matrix stored with the wrong orientation; chaining transformations where an intermediate matrix was reshaped; porting NumPy code (which broadcasts) to this strict Matrix class.","solutions":["Verify dimensions before multiplying: assert a.num_columns == b.num_rows, and print (a.num_rows, a.num_columns) and (b.num_rows, b.num_columns) to find the mismatch.","If the operands are swapped, reverse them: b * a is valid whenever b.num_columns == a.num_rows.","Transpose one operand if the data orientation is wrong: use a.transpose() (or the class's transpose method) so inner dimensions align.","Reshape or rebuild the source data so matrices are constructed with compatible dimensions at creation time."],"exampleFix":"# before\nresult = matrix_a * matrix_b  # 2x3 * 2x2 -> ValueError\n\n# after\nif matrix_a.num_columns != matrix_b.num_rows:\n    matrix_b = matrix_b.transpose()\nresult = matrix_a * matrix_b","handlingStrategy":"validation","validationCode":"def can_multiply(a: Matrix, b: Matrix) -> bool:\n    return a.num_columns == b.num_rows\n\nif not can_multiply(matrix_a, matrix_b):\n    raise ValueError(f\"cannot multiply {a.num_rows}x{a.num_columns} by {b.num_rows}x{b.num_columns}\")","typeGuard":"def are_compatible_for_mul(a: Matrix, b: Matrix) -> bool:\n    \"\"\"Type/shape guard: both are Matrix and inner dimensions align.\"\"\"\n    return isinstance(a, Matrix) and isinstance(b, Matrix) and a.num_columns == b.num_rows","tryCatchPattern":"try:\n    result = a * b\nexcept ValueError as e:\n    if \"number of columns\" in str(e):\n        b = b.transpose()\n        result = a * b\n    else:\n        raise","preventionTips":["Always print (rows, cols) of both matrices when wiring up a new multiplication pipeline.","Keep a helper assert_compatible(a, b) and call it before every Matrix * Matrix in new code.","Remember the rule: (m x n) * (n x p) -> m x p; write it next to the call while developing."],"tags":["matrix","linear-algebra","dimension-mismatch","valueerror"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}