{"record":{"id":"087dc0832a3ae35d","repo":"TheAlgorithms/Python","slug":"must-have-the-same-size","errorCode":null,"errorMessage":"must have the same size","messagePattern":"must have the same size","errorType":"exception","errorClass":"Exception","httpStatus":null,"severity":"error","filePath":"linear_algebra/src/lib.py","lineNumber":83,"sourceCode":"\n    def __str__(self) -> str:\n        \"\"\"\n        returns a string representation of the vector\n        \"\"\"\n        return \"(\" + \",\".join(map(str, self.__components)) + \")\"\n\n    def __add__(self, other: Vector) -> Vector:\n        \"\"\"\n        input: other vector\n        assumes: other vector has the same size\n        returns a new vector that represents the sum.\n        \"\"\"\n        size = len(self)\n        if size == len(other):\n            result = [self.__components[i] + other.component(i) for i in range(size)]\n            return Vector(result)\n        else:\n            raise Exception(\"must have the same size\")\n\n    def __sub__(self, other: Vector) -> Vector:\n        \"\"\"\n        input: other vector\n        assumes: other vector has the same size\n        returns a new vector that represents the difference.\n        \"\"\"\n        size = len(self)\n        if size == len(other):\n            result = [self.__components[i] - other.component(i) for i in range(size)]\n            return Vector(result)\n        else:  # error case\n            raise Exception(\"must have the same size\")\n\n    def __eq__(self, other: object) -> bool:\n        \"\"\"\n        performs the comparison between two vectors\n        \"\"\"","sourceCodeStart":65,"sourceCodeEnd":101,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/linear_algebra/src/lib.py#L65-L101","documentation":"Raised by Vector.__add__ in linear_algebra/src/lib.py:83 when the two vectors being added have different lengths. The method compares len(self) with len(other) and, on mismatch, raises a bare Exception with the terse message 'must have the same size'. Vector addition is only defined component-wise for equal dimensions.","triggerScenarios":"Using the + operator between Vector instances of different dimensions: Vector([1, 2, 3]) + Vector([1, 2]). Also hit indirectly when one vector was built from a truncated list or a loop that produced fewer components.","commonSituations":"Merging feature vectors of different schema versions, one-hot vectors built from vocabularies of different sizes, or slicing a vector and forgetting to slice the other operand to match.","solutions":["Check len(v1) == len(v2) before applying + (both Vector and plain list sizes).","Find the construction site of the shorter vector — usually one list lost or gained an element.","Pad the shorter vector with zeros if that is semantically valid for your use case.","Since this is a bare Exception, catch it narrowly (see defense) or validate beforehand rather than blanket except."],"exampleFix":"// before\nv = Vector([1, 2, 3]) + Vector([1, 2])  # Exception: must have the same size\n\n// after\nv1, v2 = Vector([1, 2, 3]), Vector([1, 2])\nif len(v1) != len(v2):\n    raise ValueError(f\"dimension mismatch: {len(v1)} vs {len(v2)}\")\nv = v1 + v2","handlingStrategy":"validation","validationCode":"def same_size(v1, v2) -> bool:\n    return len(v1) == len(v2)\n\nif not same_size(a, b):\n    raise ValueError(f\"cannot add: sizes {len(a)} and {len(b)} differ\")\nresult = a + b","typeGuard":"from linear_algebra.src.lib import Vector\n\ndef is_vector_of(obj, n: int) -> bool:\n    return isinstance(obj, Vector) and len(obj) == n","tryCatchPattern":"try:\n    result = a + b\nexcept Exception as e:  # library raises bare Exception\n    if \"same size\" in str(e):\n        raise ValueError(f\"vector size mismatch: {len(a)} vs {len(b)}\") from e\n    raise","preventionTips":["Compare len() of both Vector operands before every + on externally-sourced vectors.","Build vectors in a single factory so all vectors in a pipeline share dimensionality by construction.","Since the library throws bare Exception (not ValueError/TypeError), prefer pre-validation over catching; if you must catch, match on the message.","Add dimension assertions in tests to catch drift early when schemas change."],"tags":["linear-algebra","vector","dimension-mismatch","validation"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}