TheAlgorithms/Python · error · TypeError

Expected a matrix, got int/list instead

Error message

Expected a matrix, got int/list instead

What it means

Raised by add() in matrix_operation when any argument fails _check_not_integer, i.e. the argument is an int/float scalar or a flat (1-D) list rather than a 2-D nested-list matrix. The function sums element-wise across matrices via zip, which requires every argument to be a proper list of rows. Despite the message wording, the actual check rejects scalars and non-nested lists.

Source

Thrown at matrix/matrix_operation.py:27

def add(*matrix_s: list[list[int]]) -> list[list[int]]:
    """
    >>> add([[1,2],[3,4]],[[2,3],[4,5]])
    [[3, 5], [7, 9]]
    >>> add([[1.2,2.4],[3,4]],[[2,3],[4,5]])
    [[3.2, 5.4], [7, 9]]
    >>> add([[1, 2], [4, 5]], [[3, 7], [3, 4]], [[3, 5], [5, 7]])
    [[7, 14], [12, 16]]
    >>> add([3], [4, 5])
    Traceback (most recent call last):
      ...
    TypeError: Expected a matrix, got int/list instead
    """
    if all(_check_not_integer(m) for m in matrix_s):
        for i in matrix_s[1:]:
            _verify_matrix_sizes(matrix_s[0], i)
        return [[sum(t) for t in zip(*m)] for m in zip(*matrix_s)]
    raise TypeError("Expected a matrix, got int/list instead")


def subtract(matrix_a: list[list[int]], matrix_b: list[list[int]]) -> list[list[int]]:
    """
    >>> subtract([[1,2],[3,4]],[[2,3],[4,5]])
    [[-1, -1], [-1, -1]]
    >>> subtract([[1,2.5],[3,4]],[[2,3],[4,5.5]])
    [[-1, -0.5], [-1, -1.5]]
    >>> subtract([3], [4, 5])
    Traceback (most recent call last):
      ...
    TypeError: Expected a matrix, got int/list instead
    """
    if (
        _check_not_integer(matrix_a)
        and _check_not_integer(matrix_b)
        and _verify_matrix_sizes(matrix_a, matrix_b)
    ):

View on GitHub (pinned to f5988cc097)

Solutions

  1. Wrap scalars per-element or use scalar_multiply for scaling; do not pass scalars to add().
  2. Nest 1-D data explicitly: pass [[1, 2]] instead of [1, 2] when a one-row matrix is meant.
  3. Validate input shape at your boundary: assert isinstance(m, list) and all(isinstance(r, list) for r in m).
  4. For scalar addition to every element, write [[x + s for x in row] for row in matrix] or use scalar_multiply with s-1 trick — but prefer an explicit elementwise helper.

Example fix

# before
result = add([3], [4, 5])  # TypeError

# after
result = add([[1, 2, 3]], [[4, 5, 6]])  # proper 1x3 matrices -> [[5, 7, 9]]
Defensive patterns

Strategy: type-guard

Validate before calling

def as_matrix(m):
    """Wrap flat numeric lists as a 1-row matrix; reject scalars."""
    if isinstance(m, (int, float)):
        raise TypeError("scalars are not matrices; use scalar_multiply for scaling")
    if isinstance(m, list) and m and not isinstance(m[0], list):
        return [m]
    return m

matrix_s = [as_matrix(m) for m in matrix_s]
result = add(*matrix_s)

Type guard

def is_2d_matrix(m) -> bool:
    """Guard: non-empty list of non-empty lists (all rows lists, no scalars/flat lists)."""
    return (
        isinstance(m, list) and len(m) > 0
        and all(isinstance(row, list) and len(row) > 0 for row in m)
    )

Try / catch

try:
    result = add(a, b)
except TypeError as e:
    if "int/list instead" in str(e):
        a, b = as_matrix(a), as_matrix(b)
        result = add(a, b)
    else:
        raise

Prevention

When it happens

Trigger: add([3], [4, 5]) (flat lists), add(3, 4) (scalars), or add([[1, 2]], [3]) where one operand is 1-D. Note: ragged matrices like [[1, 2], [3]] pass this check but silently misbehave; only the shape check between matrices (_verify_matrix_sizes) catches size mismatches afterward.

Common situations: Passing a scalar broadcast-style (NumPy habit: matrix + 3); data parsed from JSON/CSV arriving as a flat list; a vector argument where a row-vector [[x, y]] was intended.

Related errors


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