{"record":{"id":"5ac60f395a2d2cfe","repo":"pandas-dev/pandas","slug":"lengths-must-match-to-compare-5ac60f","errorCode":null,"errorMessage":"Lengths must match to compare","messagePattern":"Lengths must match to compare","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/masked.py","lineNumber":1095,"sourceCode":"            other, mask = other._data, other._mask\n\n        elif 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            other = np.asarray(other)\n            if other.ndim > 1:\n                raise NotImplementedError(\"can only perform ops with 1-d structures\")\n            if len(self) != len(other):\n                raise ValueError(\"Lengths must match to compare\")\n\n        if other is libmissing.NA:\n            # numpy does not handle pd.NA well as \"other\" scalar (it returns\n            # a scalar False instead of an array)\n            # This may be fixed by NA.__array_ufunc__. Revisit this check\n            # once that's implemented.\n            result = np.zeros(self._data.shape, dtype=\"bool\")\n            mask = np.ones(self._data.shape, dtype=\"bool\")\n        else:\n            with warnings.catch_warnings():\n                # numpy may show a FutureWarning or DeprecationWarning:\n                #     elementwise comparison failed; returning scalar instead,\n                #     but in the future will perform elementwise comparison\n                # before returning NotImplemented. We fall back to the correct\n                # behavior today, so that should be fine to ignore.\n                warnings.filterwarnings(\"ignore\", \"elementwise\", FutureWarning)\n                warnings.filterwarnings(\"ignore\", \"elementwise\", DeprecationWarning)\n                method = getattr(self._data, f\"__{op.__name__}__\")","sourceCodeStart":1077,"sourceCodeEnd":1113,"githubUrl":"https://github.com/pandas-dev/pandas/blob/71959b8cb9b2459c16e14b34f28b178ccfe14735/pandas/core/arrays/masked.py#L1077-L1113","documentation":"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.","triggerScenarios":"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).","commonSituations":"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.","solutions":["Realign via index before comparing: s1 == s2 (use Series so pandas aligns), or s1.eq(s2).","Reset/recompute lengths: ensure len(other) == len(arr) by re-deriving both from the same filtered frame.","Compare against a scalar or broadcast a single value if that was intended."],"exampleFix":"// before\narr == other  # len(other) != len(arr) -> raises\n\n// after\npd.Series(arr, index=idx).eq(pd.Series(other, index=idx))","handlingStrategy":"validation","validationCode":"def assert_aligned(arr, other):\n    n = len(arr)\n    if hasattr(other, '__len__') and len(other) != n:\n        raise ValueError(f\"length mismatch: {len(other)} != {n}\")\n    return other","typeGuard":"def lengths_match(arr, other) -> bool:\n    return not hasattr(other, '__len__') or len(other) == len(arr)","tryCatchPattern":"try:\n    res = arr == other\nexcept ValueError as e:\n    if \"Lengths must match\" in str(e):\n        import pandas as pd\n        res = pd.Series(arr).eq(pd.Series(other))  # align by index\n    else:\n        raise","preventionTips":["Always derive both operands from the same filtered/indexed frame.","Prefer Series.eq for index-aligned comparison.","Add an assertion on len equality in test helpers."],"tags":["masked-array","comparison","length-mismatch","alignment"],"analyzedSha":"71959b8cb9b2459c16e14b34f28b178ccfe14735","analyzedAt":"2026-08-07T01:30:20.476Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}