TheAlgorithms/Python · error · ValueError
The number of columns in the first matrix must be equal to…
Error message
The number of columns in the first matrix must be equal to the number of rows in the second
What it means
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.
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.
Example fix
# before
result = matrix_a * matrix_b # 2x3 * 2x2 -> ValueError
# after
if matrix_a.num_columns != matrix_b.num_rows:
matrix_b = matrix_b.transpose()
result = matrix_a * matrix_b Defensive patterns
Strategy: validation
Validate before calling
def can_multiply(a: Matrix, b: Matrix) -> bool:
return a.num_columns == b.num_rows
if not can_multiply(matrix_a, matrix_b):
raise ValueError(f"cannot multiply {a.num_rows}x{a.num_columns} by {b.num_rows}x{b.num_columns}") Type guard
def are_compatible_for_mul(a: Matrix, b: Matrix) -> bool:
"""Type/shape guard: both are Matrix and inner dimensions align."""
return isinstance(a, Matrix) and isinstance(b, Matrix) and a.num_columns == b.num_rows Try / catch
try:
result = a * b
except ValueError as e:
if "number of columns" in str(e):
b = b.transpose()
result = a * b
else:
raise Prevention
- 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.
When it happens
Trigger: 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.
Common situations: 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.
Related errors
- Cannot multiply matrix of dimensions
- matrices must have the same dimension!
- matrix must have the same dimension!
- Only square matrices can be raised to a power
- power is negative
AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14).
Data as JSON: /api/errors/1b0dd0cec442169f.
Report an issue: GitHub.
Appendix: source
Thrown at matrix/matrix_class.py:325
def __sub__(self, other: Matrix) -> Matrix:
if self.order != other.order:
raise ValueError("Subtraction requires matrices of the same order")
return Matrix(
[
[self.rows[i][j] - other.rows[i][j] for j in range(self.num_columns)]
for i in range(self.num_rows)
]
)
def __mul__(self, other: Matrix | float) -> Matrix:
if isinstance(other, (int, float)):
return Matrix(
[[int(element * other) for element in row] for row in self.rows]
)
elif isinstance(other, Matrix):
if self.num_columns != other.num_rows:
raise ValueError(
"The number of columns in the first matrix must "
"be equal to the number of rows in the second"
)
return Matrix(
[
[Matrix.dot_product(row, column) for column in other.columns()]
for row in self.rows
]
)
else:
raise TypeError(
"A Matrix can only be multiplied by an int, float, or another matrix"
)
def __pow__(self, other: int) -> Matrix:
if not isinstance(other, int):
raise TypeError("A Matrix can only be raised to the power of an int")
if not self.is_square:View on GitHub (pinned to f5988cc097)