{"record":{"id":"cfd027343b65ede8","repo":"pandas-dev/pandas","slug":"lengths-must-match-to-compare","errorCode":null,"errorMessage":"Lengths must match to compare","messagePattern":"Lengths must match to compare","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/interval.py","lineNumber":719,"sourceCode":"        self._left[key] = value_left\n        self._right[key] = value_right\n\n    def _cmp_method(self, other, op):\n        # ensure pandas array for list-like and eliminate non-interval scalars\n        if is_list_like(other):\n            if not isinstance(\n                other, (list, np.ndarray, ExtensionArray)\n            ) and not ops.has_castable_attr(other):\n                warnings.warn(\n                    f\"Operation with {type(other).__name__} is deprecated. \"\n                    \"In a future version these will be treated as scalar-like. \"\n                    \"To retain the old behavior, explicitly wrap in a Series \"\n                    \"instead.\",\n                    Pandas4Warning,\n                    stacklevel=find_stack_level(),\n                )\n            if len(self) != len(other):\n                raise ValueError(\"Lengths must match to compare\")\n            other = pd_array(other)\n        elif not isinstance(other, Interval):\n            # non-interval scalar -> no matches\n            if other is NA:\n                # GH#31882\n                from pandas.core.arrays import BooleanArray\n\n                arr = np.empty(self.shape, dtype=bool)\n                mask = np.ones(self.shape, dtype=bool)\n                return BooleanArray(arr, mask)\n            return invalid_comparison(self, other, op)\n\n        # determine the dtype of the elements we want to compare\n        if isinstance(other, Interval):\n            other_dtype = pandas_dtype(\"interval\")\n        elif not isinstance(other.dtype, CategoricalDtype):\n            other_dtype = other.dtype\n        else:","sourceCodeStart":701,"sourceCodeEnd":737,"githubUrl":"https://github.com/pandas-dev/pandas/blob/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/arrays/interval.py#L701-L737","documentation":"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.","triggerScenarios":"`arr == [pd.Interval(0,1)]` where arr has length 3; comparing against a list/Series shorter or longer than the array.","commonSituations":"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.","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."],"exampleFix":"# before (len mismatch)\narr == [pd.Interval(0,1)]  # arr has length 3\n\n# after\narr == pd.Interval(0,1)  # scalar broadcast","handlingStrategy":"validation","validationCode":"import pandas as pd\nfrom pandas.api.types import is_list_like\n\ndef compare_interval_array(arr, other):\n    if is_list_like(other) and len(other) != len(arr):\n        if len(other) == 1:\n            other = other[0]  # treat as scalar\n        else:\n            raise ValueError('length mismatch in comparison')\n    return arr == other","typeGuard":"from pandas.api.types import is_list_like\n\ndef length_matches_or_scalar(arr, other) -> bool:\n    if not is_list_like(other):\n        return True\n    return len(other) == len(arr)","tryCatchPattern":"try:\n    res = arr == other\nexcept ValueError as e:\n    if 'Lengths must match to compare' in str(e) and hasattr(other, '__len__') and len(other) == 1:\n        res = arr == other[0]\n    else:\n        raise","preventionTips":["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."],"tags":["interval","comparison","length-mismatch","value-error"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}