{"record":{"id":"c6d7224401891870","repo":"TheAlgorithms/Python","slug":"expected-a-matrix-got-int-list-instead","errorCode":null,"errorMessage":"Expected a matrix, got int/list instead","messagePattern":"Expected a matrix, got int/list instead","errorType":"exception","errorClass":"TypeError","httpStatus":null,"severity":"error","filePath":"matrix/matrix_operation.py","lineNumber":27,"sourceCode":"\ndef add(*matrix_s: list[list[int]]) -> list[list[int]]:\n    \"\"\"\n    >>> add([[1,2],[3,4]],[[2,3],[4,5]])\n    [[3, 5], [7, 9]]\n    >>> add([[1.2,2.4],[3,4]],[[2,3],[4,5]])\n    [[3.2, 5.4], [7, 9]]\n    >>> add([[1, 2], [4, 5]], [[3, 7], [3, 4]], [[3, 5], [5, 7]])\n    [[7, 14], [12, 16]]\n    >>> add([3], [4, 5])\n    Traceback (most recent call last):\n      ...\n    TypeError: Expected a matrix, got int/list instead\n    \"\"\"\n    if all(_check_not_integer(m) for m in matrix_s):\n        for i in matrix_s[1:]:\n            _verify_matrix_sizes(matrix_s[0], i)\n        return [[sum(t) for t in zip(*m)] for m in zip(*matrix_s)]\n    raise TypeError(\"Expected a matrix, got int/list instead\")\n\n\ndef subtract(matrix_a: list[list[int]], matrix_b: list[list[int]]) -> list[list[int]]:\n    \"\"\"\n    >>> subtract([[1,2],[3,4]],[[2,3],[4,5]])\n    [[-1, -1], [-1, -1]]\n    >>> subtract([[1,2.5],[3,4]],[[2,3],[4,5.5]])\n    [[-1, -0.5], [-1, -1.5]]\n    >>> subtract([3], [4, 5])\n    Traceback (most recent call last):\n      ...\n    TypeError: Expected a matrix, got int/list instead\n    \"\"\"\n    if (\n        _check_not_integer(matrix_a)\n        and _check_not_integer(matrix_b)\n        and _verify_matrix_sizes(matrix_a, matrix_b)\n    ):","sourceCodeStart":9,"sourceCodeEnd":45,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/matrix/matrix_operation.py#L9-L45","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Wrap scalars per-element or use scalar_multiply for scaling; do not pass scalars to add().","Nest 1-D data explicitly: pass [[1, 2]] instead of [1, 2] when a one-row matrix is meant.","Validate input shape at your boundary: assert isinstance(m, list) and all(isinstance(r, list) for r in m).","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."],"exampleFix":"# before\nresult = add([3], [4, 5])  # TypeError\n\n# after\nresult = add([[1, 2, 3]], [[4, 5, 6]])  # proper 1x3 matrices -> [[5, 7, 9]]","handlingStrategy":"type-guard","validationCode":"def as_matrix(m):\n    \"\"\"Wrap flat numeric lists as a 1-row matrix; reject scalars.\"\"\"\n    if isinstance(m, (int, float)):\n        raise TypeError(\"scalars are not matrices; use scalar_multiply for scaling\")\n    if isinstance(m, list) and m and not isinstance(m[0], list):\n        return [m]\n    return m\n\nmatrix_s = [as_matrix(m) for m in matrix_s]\nresult = add(*matrix_s)","typeGuard":"def is_2d_matrix(m) -> bool:\n    \"\"\"Guard: non-empty list of non-empty lists (all rows lists, no scalars/flat lists).\"\"\"\n    return (\n        isinstance(m, list) and len(m) > 0\n        and all(isinstance(row, list) and len(row) > 0 for row in m)\n    )","tryCatchPattern":"try:\n    result = add(a, b)\nexcept TypeError as e:\n    if \"int/list instead\" in str(e):\n        a, b = as_matrix(a), as_matrix(b)\n        result = add(a, b)\n    else:\n        raise","preventionTips":["Never pass scalars to add(); this library does not broadcast.","Nest 1-D data explicitly: [[1, 2, 3]] for a row vector.","Validate nested-list shape once at the ingestion boundary (JSON/CSV parsers are the usual source of flat lists)."],"tags":["matrix","typeerror","input-validation","shape-error"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}