pandas-dev/pandas · error · ValueError
Lengths must match
Error message
Lengths must match
What it means
Raised by DatetimeLikeArrayMixin._validate_comparison_value when comparing the array against a list-like whose length differs from the array's. Element-wise comparison requires equal lengths; broadcasting rules for datetime-like arrays do not auto-broadcast a mismatched-length list. This guard runs before the comparison so a clean ValueError is surfaced.
Source
Thrown at pandas/core/arrays/datetimelike.py:510
# failed to parse as Timestamp/Timedelta/Period
raise InvalidComparison(other) from err
if isinstance(other, self._recognized_scalars) or other is NaT:
# error: Argument 1 to "Timestamp" has incompatible type "object";
# expected "integer[Any] | float | str | date | datetime |
# datetime64[date | int | None]" [arg-type]
other = self._scalar_type(other) # type: ignore[arg-type]
try:
self._check_compatible_with(other)
except TypeError as err:
# e.g. tzawareness mismatch
raise InvalidComparison(other) from err
elif not is_list_like(other):
raise InvalidComparison(other)
elif len(other) != len(self):
raise ValueError("Lengths must match")
else:
try:
other = self._validate_listlike(other, allow_object=True)
self._check_compatible_with(other)
except TypeError as err:
if is_object_dtype(getattr(other, "dtype", None)):
# We will have to operate element-wise
pass
else:
raise InvalidComparison(other) from err
return other
def _validate_scalar(
self,
value,
*,View on GitHub (pinned to 71959b8cb9)
Solutions
- Ensure both sides have the same length, or use a scalar for broadcasting.
- Align via index: reindex or construct a Series with a matching index and let pandas align.
- Validate len(other) == len(array) before the comparison.
Example fix
// before
ts = pd.date_range('2020', periods=3)
ts == [pd.Timestamp('2020-01-01'), pd.Timestamp('2020-01-02')] # ValueError
// after
ts == [pd.Timestamp('2020-01-01')]*3 # broadcast scalar list of correct length Defensive patterns
Strategy: validation
Validate before calling
def compare_safe(arr, other):
import pandas as pd
if pd.api.types.is_list_like(other) and len(other) != len(arr):
raise ValueError(f'length {len(other)} != {len(arr)}')
return arr == other Type guard
import pandas as pd
from typing import Any
def lengths_match(a: Any, b: Any) -> bool:
if pd.api.types.is_list_like(b):
return len(a) == len(b)
return True Try / catch
try:
arr == other
except ValueError as e:
if 'Lengths must match' in str(e):
arr == [other[0]] * len(arr)
else:
raise Prevention
- Verify len(other) == len(arr) for list-like comparisons.
- Use scalars for broadcasting, lists only for element-wise compare.
When it happens
Trigger: datetime_array == [1,2,3] where the right side has a different length; Series of length N compared with a list of length M; comparison ops (<, >, ==, !=) between a datetime Series and a list/array/Index of mismatched length that is not a scalar.
Common situations: Passing a list derived from another column or a filtered subset without realigning the index; building a boolean mask from external data of the wrong length.
Related errors
- Cannot compare tz-naive and tz-aware datetime-like objects.
- Cannot compare tz-naive and tz-aware datetime-like objects
- [datetimelike_compat=True] {left._values} is not equal to {r
- overflow in timedelta operation
- Cannot compare types {!r} and {!r}
AI-assisted analysis of pandas-dev/pandas@71959b8cb9 (2026-08-07).
Data as JSON: /api/errors/eeb9c657b3290ee0.
Report an issue: GitHub.