{"record":{"id":"d2c1d1d257abc553","repo":"pandas-dev/pandas","slug":"lengths-must-match-d2c1d1","errorCode":null,"errorMessage":"Lengths must match.","messagePattern":"Lengths must match\\.","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/categorical.py","lineNumber":137,"sourceCode":"    )\n\n    from pandas import (\n        DataFrame,\n        Index,\n        Series,\n    )\n\n\ndef _cat_compare_op(op):\n    opname = f\"__{op.__name__}__\"\n    fill_value = op is operator.ne\n\n    @unpack_zerodim_and_defer(opname)\n    def func(self, other):\n        hashable = is_hashable(other)\n        if is_list_like(other) and len(other) != len(self) and not hashable:\n            # in hashable case we may have a tuple that is itself a category\n            raise ValueError(\"Lengths must match.\")\n\n        if not self.ordered:\n            if opname in [\"__lt__\", \"__gt__\", \"__le__\", \"__ge__\"]:\n                raise TypeError(\n                    \"Unordered Categoricals can only compare equality or not\"\n                )\n        if isinstance(other, Categorical):\n            # Two Categoricals can only be compared if the categories are\n            # the same (maybe up to ordering, depending on ordered)\n\n            msg = \"Categoricals can only be compared if 'categories' are the same.\"\n            if not self._categories_match_up_to_permutation(other):\n                raise TypeError(msg)\n\n            if not self.ordered and not self.categories.equals(other.categories):\n                # both unordered and different order\n                other_codes = recode_for_categories(\n                    other.codes, other.categories, self.categories, copy=False","sourceCodeStart":119,"sourceCodeEnd":155,"githubUrl":"https://github.com/pandas-dev/pandas/blob/71959b8cb9b2459c16e14b34f28b178ccfe14735/pandas/core/arrays/categorical.py#L119-L155","documentation":"Raised inside the categorical comparison operator wrapper (_cat_compare_op) when `other` is a non-hashable list-like whose length differs from the Categorical's length. Pandas only allows length-mismatched comparisons when `other` is a hashable scalar (e.g. a tuple that is itself a category); otherwise element-wise comparison requires equal lengths.","triggerScenarios":"Comparing a Categorical against a list/Series/array of a different length, e.g. `cat < [1, 2]` where cat has 3 elements. Triggered by any of __lt__, __gt__, __le__, __ge__, __eq__, __ne__ when the right-hand side is list-like and not hashable.","commonSituations":"Joining/grouping then comparing a categorical column with a list whose derivation dropped entries; or passing a hand-built list of expected categories that doesn't match row count.","solutions":["Make `other` the same length as the Categorical, or reduce `other` to a single hashable scalar if you meant a per-element comparison to one value.","If you intended set membership, use `cat.isin(other)` instead of `cat == other`.","Align both sides through a DataFrame/Series index so lengths stay synchronized."],"exampleFix":"# before\ncat = pd.Categorical(['a', 'b', 'c'])\nres = cat == ['a', 'b']\n# after\ncat = pd.Categorical(['a', 'b', 'c'])\nres = cat == ['a', 'b', 'a']","handlingStrategy":"validation","validationCode":"def safe_cat_compare(cat, other, op):\n    import numpy as np\n    from pandas.api.types import is_list_like, is_hashable\n    if is_list_like(other) and not is_hashable(other) and len(other) != len(cat):\n        raise ValueError(f\"other len {len(other)} != cat len {len(cat)}\")\n    return op(cat, other)","typeGuard":"null","tryCatchPattern":"try:\n    res = cat == other\nexcept ValueError as e:\n    if 'Lengths must match' in str(e):\n        # align or scalarize `other`\n        pass\n    raise","preventionTips":["Use cat.isin(other) for membership rather than cat == other with a list.","Keep categorical comparisons against scalars or aligned Series.","Reindex both operands to a shared index before comparing."],"tags":["categorical","length-mismatch","comparison","valueerror"],"analyzedSha":"71959b8cb9b2459c16e14b34f28b178ccfe14735","analyzedAt":"2026-08-07T01:30:20.476Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}