{"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/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/arrays/masked.py#L1077-L1113","documentation":"Raised by BaseMaskedArray._comparison_method when 'other' is a 1-D list-like whose length differs from len(self). Element-wise comparison between masked arrays and 1-D structures requires equal length; pandas does not rebroadcast or pad.","triggerScenarios":"Comparing two masked arrays/Series of different lengths: arr1 == arr2 where len(arr1) != len(arr2); passing a list whose length differs from the array.","commonSituations":"Comparing columns from misaligned DataFrames without reindexing; comparing against a list literal of the wrong length; off-by-one after slicing or filtering.","solutions":["Reindex or align both sides to a shared index before comparing.","Trim or extend the operand so lengths match (e.g. other[:len(arr)]).","Compare against a scalar or use isin() for membership tests instead of ==."],"exampleFix":"// before\narr == other[len(arr) - 1:]   # wrong length\n// after\naligned = other[:len(arr)]\narr == aligned","handlingStrategy":"validation","validationCode":"import numpy as np\nother_arr = np.asarray(other)\nif other_arr.ndim == 1 and len(other_arr) != len(arr):\n    raise ValueError(f'Length mismatch: {len(arr)} vs {len(other_arr)}')\nresult = arr == other_arr","typeGuard":"def lengths_match(arr, other) -> bool:\n    import numpy as np\n    if np.isscalar(other):\n        return True\n    return len(other) == len(arr)","tryCatchPattern":"try:\n    result = arr == other\nexcept ValueError as e:\n    if 'Lengths must match' in str(e):\n        other = other[:len(arr)]\n        result = arr == other\n    else:\n        raise","preventionTips":["Align indexes (reindex) before comparing columns of different lengths.","Slice or pad operands to len(arr) explicitly when intent is clear.","Use isin for membership rather than == against arbitrary-length lists."],"tags":["pandas","masked-array","comparison","length-mismatch"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}