TheAlgorithms/Python · error · Exception

Matrices are not 2x2

Error message

Matrices are not 2x2

What it means

Raised by default_matrix_multiplication in strassen_matrix_multiplication.py, a helper that only multiplies exactly 2x2 matrices. It checks len(a) == 2, len(a[0]) == 2 and the same for b, and raises a bare Exception otherwise. This helper is the recursion base case for Strassen's algorithm; only your own code should hit it if you call it directly with larger or ragged matrices.

Source

Thrown at divide_and_conquer/strassen_matrix_multiplication.py:11

from __future__ import annotations

import math


def default_matrix_multiplication(a: list, b: list) -> list:
    """
    Multiplication only for 2x2 matrices
    """
    if len(a) != 2 or len(a[0]) != 2 or len(b) != 2 or len(b[0]) != 2:
        raise Exception("Matrices are not 2x2")
    new_matrix = [
        [a[0][0] * b[0][0] + a[0][1] * b[1][0], a[0][0] * b[0][1] + a[0][1] * b[1][1]],
        [a[1][0] * b[0][0] + a[1][1] * b[1][0], a[1][0] * b[0][1] + a[1][1] * b[1][1]],
    ]
    return new_matrix


def matrix_addition(matrix_a: list, matrix_b: list):
    return [
        [matrix_a[row][col] + matrix_b[row][col] for col in range(len(matrix_a[row]))]
        for row in range(len(matrix_a))
    ]


def matrix_subtraction(matrix_a: list, matrix_b: list):
    return [
        [matrix_a[row][col] - matrix_b[row][col] for col in range(len(matrix_a[row]))]
        for row in range(len(matrix_a))

View on GitHub (pinned to f5988cc097)

Solutions

  1. Use the public strassen(matrix1, matrix2) function instead, which handles arbitrary rectangular dimensions via zero-padding.
  2. If you must call this helper, first split/pad matrices to exactly 2x2 (e.g. via split_matrix or manual slicing).
  3. Validate row lengths before the call: assert len(m) == 2 and all(len(r) == 2 for r in m).

Example fix

# before
product = default_matrix_multiplication(a, b)  # a is 3x3 -> Exception

# after
from divide_and_conquer.strassen_matrix_multiplication import strassen
product = strassen(a, b)
Defensive patterns

Strategy: validation

Validate before calling

def is_2x2(m) -> bool:
    return (
        isinstance(m, list) and len(m) == 2
        and all(isinstance(r, list) and len(r) == 2 for r in m)
    )

if is_2x2(a) and is_2x2(b):
    product = default_matrix_multiplication(a, b)

Type guard

from typing import List, Union
Number = Union[int, float]

def is_matrix_2x2(m: object) -> bool:
    return isinstance(m, list) and len(m) == 2 and all(isinstance(m[i], list) and len(m[i]) == 2 for i in range(2))

Try / catch

try:
    product = default_matrix_multiplication(a, b)
except Exception as exc:
    if 'Matrices are not 2x2' in str(exc):
        raise ValueError('reshape inputs to 2x2 or use strassen()') from exc
    raise

Prevention

When it happens

Trigger: Calling default_matrix_multiplication with 1x1, 3x3, NxM matrices, or 2-row matrices whose rows are not length 2 (ragged input such as [[1,2,3],[4]]). The public strassen() entry point pads dimensions itself and does not raise this.

Common situations: Reusing this private helper as a general matrix multiplier; passing a matrix of floats/rows built by parsing CSV where row lengths differ; copying the base-case call into custom recursion that forgets to split to 2x2.

Related errors


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