{"record":{"id":"1723e88ea4649597","repo":"pandas-dev/pandas","slug":"lengths-must-match","errorCode":null,"errorMessage":"Lengths must match","messagePattern":"Lengths must match","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/boolean.py","lineNumber":427,"sourceCode":"                    Pandas4Warning,\n                    stacklevel=find_stack_level(),\n                )\n\n            other = np.asarray(other, dtype=\"bool\")\n            if other.ndim > 1:\n                return NotImplemented\n            other, mask = coerce_to_array(other, copy=False)\n        elif isinstance(other, np.bool_):\n            other = other.item()\n\n        if other_is_scalar and other is not libmissing.NA and not lib.is_bool(other):\n            raise TypeError(\n                \"'other' should be pandas.NA or a bool. \"\n                f\"Got {type(other).__name__} instead.\"\n            )\n\n        if not other_is_scalar and len(self) != len(other):\n            raise ValueError(\"Lengths must match\")\n\n        if op.__name__ in {\"or_\", \"ror_\"}:\n            result, mask = ops.kleene_or(self._data, other, self._mask, mask)\n        elif op.__name__ in {\"and_\", \"rand_\"}:\n            result, mask = ops.kleene_and(self._data, other, self._mask, mask)\n        else:\n            # i.e. xor, rxor\n            result, mask = ops.kleene_xor(self._data, other, self._mask, mask)\n\n        # i.e. BooleanArray\n        return self._maybe_mask_result(result, mask)\n\n    def _accumulate(\n        self, name: str, *, skipna: bool = True, **kwargs\n    ) -> BaseMaskedArray:\n        data = self._data\n        mask = self._mask\n        if name in (\"cummin\", \"cummax\"):","sourceCodeStart":409,"sourceCodeEnd":445,"githubUrl":"https://github.com/pandas-dev/pandas/blob/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/arrays/boolean.py#L409-L445","documentation":"Raised by BooleanArray._logical_method when 'other' is array-like (not scalar) and its length differs from self. BooleanArray logical ops are element-wise, so the operands must align in length; otherwise the result would be ill-defined. The check fires before the Kleene dispatch.","triggerScenarios":"boolean_series & pd.array([True, False], dtype='boolean') of a different length; boolean_array | [True, False, True, True] against a 3-element BooleanArray; mixing a BooleanArray with a list-like operand of mismatched length in &, |, ^.","commonSituations":"Broadcasting mistakes; operands drawn from columns of different DataFrames without alignment; off-by-one after filtering one operand but not the other; using a Python list of the wrong length.","solutions":["Align the operands via a common pandas Index before the operation (Series will reindex).","Broadcast a scalar instead of a length-mismatched array when you meant element-wise-constant.","Verify len(other) == len(self) before the operation and trim/extend as needed."],"exampleFix":"// before\ns = pd.Series(pd.array([True, False, None], dtype='boolean'))\nout = s & pd.array([True, False], dtype='boolean')\n// after\ns = pd.Series(pd.array([True, False, None], dtype='boolean'))\nother = pd.Series(pd.array([True, False, True], dtype='boolean'), index=s.index)\nout = s & other","handlingStrategy":"validation","validationCode":"if not lib.is_scalar(other) and len(self) != len(other):\n    raise ValueError(f'length mismatch: {len(self)} vs {len(other)}')","typeGuard":"def lengths_aligned(self_arr, other) -> bool:\n    from pandas._libs import lib\n    return lib.is_scalar(other) or len(self_arr) == len(other)","tryCatchPattern":"try:\n    result = boolean_array & other\nexcept ValueError as e:\n    if 'Lengths must match' in str(e):\n        other = other.reindex(boolean_array.index)\n        ...","preventionTips":["Align operands to a common pandas Index before element-wise ops.","Use Series-backed BooleanArray operands to get automatic alignment."],"tags":["boolean","logical","length","kleene","alignment"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}