pandas-dev/pandas · error · ValueError
Lengths must match to compare
Error message
Lengths must match to compare
What it means
Raised in `_cmp_method` when `other` is list-like (after the deprecation warning for non-castable types) but `len(self) != len(other)`. Comparison broadcasts require equal lengths; pandas refuses to broadcast list-likes of different length against the IntervalArray.
Solutions
- For scalar comparison, pass a single Interval (not a list): `arr == pd.Interval(0,1)`.
- Align lengths: filter the comparison operand with the same mask as the array.
- Broadcast explicitly via a Series reindex if you want position-aligned comparison.
Example fix
# before (len mismatch) arr == [pd.Interval(0,1)] # arr has length 3 # after arr == pd.Interval(0,1) # scalar broadcast
Defensive patterns
Strategy: validation
Validate before calling
import pandas as pd
from pandas.api.types import is_list_like
def compare_interval_array(arr, other):
if is_list_like(other) and len(other) != len(arr):
if len(other) == 1:
other = other[0] # treat as scalar
else:
raise ValueError('length mismatch in comparison')
return arr == other Type guard
from pandas.api.types import is_list_like
def length_matches_or_scalar(arr, other) -> bool:
if not is_list_like(other):
return True
return len(other) == len(arr) Try / catch
try:
res = arr == other
except ValueError as e:
if 'Lengths must match to compare' in str(e) and hasattr(other, '__len__') and len(other) == 1:
res = arr == other[0]
else:
raise Prevention
- Pass a bare Interval for scalar broadcast comparison, not a 1-element list.
- Align comparison operands to the array's length.
- Use a Series reindex for position-aligned list comparisons.
When it happens
Trigger: `arr == [pd.Interval(0,1)]` where arr has length 3; comparing against a list/Series shorter or longer than the array.
Common situations: Comparing against a single-element list expecting scalar broadcast (use a bare Interval instead); mismatched filter results; passing a column of a differently-shaped DataFrame.
Related errors
- left and right must have the same length
- Cannot modify read-only array
- closed keyword does not match dtype.closed
- invalid dtype
- left and right must have the same time zone, got
AI-assisted analysis of pandas-dev/pandas@3b7651241d (2026-08-11).
Data as JSON: /api/errors/cfd027343b65ede8.
Report an issue: GitHub.
Appendix: source
Thrown at pandas/core/arrays/interval.py:719
self._left[key] = value_left
self._right[key] = value_right
def _cmp_method(self, other, op):
# ensure pandas array for list-like and eliminate non-interval scalars
if is_list_like(other):
if not isinstance(
other, (list, np.ndarray, ExtensionArray)
) and not ops.has_castable_attr(other):
warnings.warn(
f"Operation with {type(other).__name__} is deprecated. "
"In a future version these will be treated as scalar-like. "
"To retain the old behavior, explicitly wrap in a Series "
"instead.",
Pandas4Warning,
stacklevel=find_stack_level(),
)
if len(self) != len(other):
raise ValueError("Lengths must match to compare")
other = pd_array(other)
elif not isinstance(other, Interval):
# non-interval scalar -> no matches
if other is NA:
# GH#31882
from pandas.core.arrays import BooleanArray
arr = np.empty(self.shape, dtype=bool)
mask = np.ones(self.shape, dtype=bool)
return BooleanArray(arr, mask)
return invalid_comparison(self, other, op)
# determine the dtype of the elements we want to compare
if isinstance(other, Interval):
other_dtype = pandas_dtype("interval")
elif not isinstance(other.dtype, CategoricalDtype):
other_dtype = other.dtype
else:View on GitHub (pinned to 3b7651241d)