pandas-dev/pandas · error · ValueError

Lengths must match to compare

Error message

Lengths must match to compare

What it means

Raised by `_cmp_method` (the engine behind `==`, `!=`, `<`, etc.) when comparing against a list-like whose length differs from the IntervalArray. Broadcasting-style comparisons are not allowed for unequal-length array operands. Fires at pandas/core/arrays/interval.py:719.

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 71959b8cb9)

Solutions

  1. Wrap scalar comparisons as a scalar: `ia == pd.Interval(0,1)` (no list).
  2. Align both sides: `ia.align(other)` or reindex to a common index.
  3. Broadcast explicitly: `ia == np.repeat(other, len(ia))` when you really mean elementwise-repeat.

Example fix

// before
ia == [pd.Interval(0, 1)]
// after
ia == pd.Interval(0, 1)
Defensive patterns

Strategy: validation

Validate before calling

import pandas as pd

def compare_interval(ia, other):
    if pd.api.types.is_list_like(other) and not isinstance(other, pd.Interval):
        if len(other) != len(ia):
            raise ValueError(f"length mismatch: {len(ia)} vs {len(other)}")
    return ia == other

Type guard

import pandas as pd
from pandas.api.types import is_list_like

def lengths_match_or_scalar(ia, other) -> bool:
    return not is_list_like(other) or len(other) == len(ia)

Try / catch

try:
    result = ia == other
except ValueError as e:
    if "Lengths must match" in str(e):
        result = ia == pd.Interval(other[0].left, other[0].right)  # if intent was scalar
    else:
        raise

Prevention

When it happens

Trigger: `ia == [pd.Interval(0,1)]` where `len(ia) != 1`, or comparing two Series of intervals of different lengths.

Common situations: Comparing an interval column against a single-element list (intended as scalar), or after filtering one side.

Related errors


AI-assisted analysis of pandas-dev/pandas@71959b8cb9 (2026-08-07). Data as JSON: /api/errors/cfd027343b65ede8. Report an issue: GitHub.