pandas-dev/pandas · error · ValueError

Lengths must match to compare

Error message

Lengths must match to compare

What it means

Raised by BaseMaskedArray._comparison_method when the right operand is a list-like whose length differs from len(self). Elementwise comparison requires aligned lengths; unlike numpy (which may return a scalar False with a warning), pandas raises to surface the bug.

Source

Thrown at pandas/core/arrays/masked.py:1095

            other, mask = other._data, other._mask

        elif 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(),
                )
            other = np.asarray(other)
            if other.ndim > 1:
                raise NotImplementedError("can only perform ops with 1-d structures")
            if len(self) != len(other):
                raise ValueError("Lengths must match to compare")

        if other is libmissing.NA:
            # numpy does not handle pd.NA well as "other" scalar (it returns
            # a scalar False instead of an array)
            # This may be fixed by NA.__array_ufunc__. Revisit this check
            # once that's implemented.
            result = np.zeros(self._data.shape, dtype="bool")
            mask = np.ones(self._data.shape, dtype="bool")
        else:
            with warnings.catch_warnings():
                # numpy may show a FutureWarning or DeprecationWarning:
                #     elementwise comparison failed; returning scalar instead,
                #     but in the future will perform elementwise comparison
                # before returning NotImplemented. We fall back to the correct
                # behavior today, so that should be fine to ignore.
                warnings.filterwarnings("ignore", "elementwise", FutureWarning)
                warnings.filterwarnings("ignore", "elementwise", DeprecationWarning)
                method = getattr(self._data, f"__{op.__name__}__")

View on GitHub (pinned to 71959b8cb9)

Solutions

  1. Realign via index before comparing: s1 == s2 (use Series so pandas aligns), or s1.eq(s2).
  2. Reset/recompute lengths: ensure len(other) == len(arr) by re-deriving both from the same filtered frame.
  3. Compare against a scalar or broadcast a single value if that was intended.

Example fix

// before
arr == other  # len(other) != len(arr) -> raises

// after
pd.Series(arr, index=idx).eq(pd.Series(other, index=idx))
Defensive patterns

Strategy: validation

Validate before calling

def assert_aligned(arr, other):
    n = len(arr)
    if hasattr(other, '__len__') and len(other) != n:
        raise ValueError(f"length mismatch: {len(other)} != {n}")
    return other

Type guard

def lengths_match(arr, other) -> bool:
    return not hasattr(other, '__len__') or len(other) == len(arr)

Try / catch

try:
    res = arr == other
except ValueError as e:
    if "Lengths must match" in str(e):
        import pandas as pd
        res = pd.Series(arr).eq(pd.Series(other))  # align by index
    else:
        raise

Prevention

When it happens

Trigger: Comparing arr (length n) against another list-like/ndarray/Series of length m != n, e.g. arr == other_arr where len(other_arr) != len(arr).

Common situations: Misaligned columns after a filter/groupby that changed lengths; comparing a Series against a slice taken from a different index; refactoring that dropped rows on one side only.

Related errors


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