{"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/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/arrays/categorical.py#L119-L155","documentation":"Raised inside the comparison operator built by `_cat_compare_op` when `other` is a list-like whose length differs from the Categorical and `other` is not hashable. Pandas requires element-wise comparisons against list-likes to be broadcastable (equal length). The hashable carve-out exists so a single tuple that is itself a category is treated as a scalar, not a sequence.","triggerScenarios":"Calling any comparison operator (`==`, `!=`, `<`, `>`, `<=`, `>=`) on a Categorical with a Python list, numpy array, Series, or Index whose `len()` differs from `len(cat)` — e.g. `pd.Categorical(['a','b','c']) == ['a','b']`.","commonSituations":"Mismatched index alignment expectations (users assume pandas auto-aligns like Series does — it does not for raw Categorical ops), broadcasting a scalar accidentally wrapped in a list, or feeding a column from a differently-filtered DataFrame.","solutions":["Verify `len(other) == len(cat)` before comparing; align or filter the list-like to match.","If you meant scalar comparison, pass the scalar directly (not wrapped in a list/tuple).","For index-aligned comparison, wrap both sides in a Series first: `pd.Series(cat) == pd.Series(other)`.","If comparing against a single tuple-as-category, ensure the tuple is itself hashable and present in `cat.categories`."],"exampleFix":"# before\nimport pandas as pd\ncat = pd.Categorical(['a', 'b', 'c'])\nresult = cat == ['a', 'b']  # ValueError: Lengths must match.\n\n# after (scalar)\nresult = cat == 'a'\n# after (aligned list-like)\nresult = cat == ['a', 'b', 'c']","handlingStrategy":"validation","validationCode":"import numpy as np\nfrom pandas.api.types import is_list_like\n\ndef safe_cat_compare(cat, other):\n    if is_list_like(other) and len(other) != len(cat):\n        raise ValueError(f\"length {len(other)} != {len(cat)}; align before compare\")\n    return cat == other","typeGuard":"from pandas.api.types import is_list_like, is_hashable\n\ndef is_broadcastable_to(cat, other) -> bool:\n    if not is_list_like(other) or is_hashable(other):\n        return True\n    return len(other) == len(cat)","tryCatchPattern":"try:\n    result = cat == other\nexcept ValueError as e:\n    if \"Lengths must match\" in str(e):\n        # align lengths, then retry\n        ...\n    raise","preventionTips":["Always confirm `len(other) == len(cat)` before element-wise comparisons against list-likes.","Prefer Series-on-Series comparison if you want automatic index alignment.","Wrap scalars in their natural form (not single-element lists) so they hit the hashable branch."],"tags":["categorical","comparison","length-mismatch","valueerror"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}