TheAlgorithms/Python · error · Exception
must have the same size
Error message
must have the same size
What it means
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.
Source
Thrown at linear_algebra/src/lib.py:83
def __str__(self) -> str:
"""
returns a string representation of the vector
"""
return "(" + ",".join(map(str, self.__components)) + ")"
def __add__(self, other: Vector) -> Vector:
"""
input: other vector
assumes: other vector has the same size
returns a new vector that represents the sum.
"""
size = len(self)
if size == len(other):
result = [self.__components[i] + other.component(i) for i in range(size)]
return Vector(result)
else:
raise Exception("must have the same size")
def __sub__(self, other: Vector) -> Vector:
"""
input: other vector
assumes: other vector has the same size
returns a new vector that represents the difference.
"""
size = len(self)
if size == len(other):
result = [self.__components[i] - other.component(i) for i in range(size)]
return Vector(result)
else: # error case
raise Exception("must have the same size")
def __eq__(self, other: object) -> bool:
"""
performs the comparison between two vectors
"""View on GitHub (pinned to f5988cc097)
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.
Example fix
// before
v = Vector([1, 2, 3]) + Vector([1, 2]) # Exception: must have the same size
// after
v1, v2 = Vector([1, 2, 3]), Vector([1, 2])
if len(v1) != len(v2):
raise ValueError(f"dimension mismatch: {len(v1)} vs {len(v2)}")
v = v1 + v2 Defensive patterns
Strategy: validation
Validate before calling
def same_size(v1, v2) -> bool:
return len(v1) == len(v2)
if not same_size(a, b):
raise ValueError(f"cannot add: sizes {len(a)} and {len(b)} differ")
result = a + b Type guard
from linear_algebra.src.lib import Vector
def is_vector_of(obj, n: int) -> bool:
return isinstance(obj, Vector) and len(obj) == n Try / catch
try:
result = a + b
except Exception as e: # library raises bare Exception
if "same size" in str(e):
raise ValueError(f"vector size mismatch: {len(a)} vs {len(b)}") from e
raise Prevention
- 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.
When it happens
Trigger: 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.
Common situations: 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.
Related errors
- vector must have the same size as the number of columns of t
- index out of range
- Vector is empty
- matrix must have the same dimension!
- matrices must have the same dimension!
AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14).
Data as JSON: /api/errors/087dc0832a3ae35d.
Report an issue: GitHub.