{"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/71959b8cb9b2459c16e14b34f28b178ccfe14735/pandas/core/arrays/boolean.py#L409-L445","documentation":"Raised by BooleanArray's bitwise logical operators (_arithmethod) when a non-scalar operand's length differs from the array's length. Pandas requires element-wise logical ops (& | ^) between a BooleanArray (nullable 'boolean' dtype) and a list-like to be broadcastable to the same length, unlike scalars which broadcast freely.","triggerScenarios":"Calling `mask_arr & other`, `mask_arr | other`, or `mask_arr ^ other` where `mask_arr` is a pandas BooleanArray and `other` is a list/ndarray/Series whose len() != len(mask_arr). For example `pd.array([True, False, True], dtype='boolean') & [True, False]`.","commonSituations":"Mistakenly pairing a boolean mask column with a differently-sized list after filtering rows, dropping NaNs, or reindexing; or feeding a Python list of bools that was built independently of the DataFrame column length.","solutions":["Verify len(other) == len(mask_arr) before the operation and trim/reindex `other` to match.","If comparing against a single value, pass a scalar (True/False/pd.NA) instead of a 1-element list so it broadcasts.","Align via the DataFrame index: `mask_arr & df['other_col']` rather than `mask_arr & df['other_col'].tolist()` after row filtering.","Use numpy arrays of equal length constructed from the same source to guarantee alignment."],"exampleFix":"// before\nm = pd.array([True, False, True], dtype=\"boolean\")\nout = m & [True, False]\n// after\nm = pd.array([True, False, True], dtype=\"boolean\")\nout = m & [True, False, True]","handlingStrategy":"validation","validationCode":"import numpy as np\n\ndef safe_bool_and(arr, other):\n    other = np.asarray(other, dtype=bool) if not np.isscalar(other) else other\n    if not np.isscalar(other) and len(other) != len(arr):\n        raise ValueError(f\"length {len(other)} != {len(arr)}\")\n    return arr & other","typeGuard":"def is_bool_array_of_len(x, n) -> bool:\n    import pandas as pd\n    return isinstance(x, (pd.array,)) and getattr(x, 'dtype', None) == 'boolean' or hasattr(x, '__len__') and len(x) == n","tryCatchPattern":"try:\n    result = mask_arr & other\nexcept ValueError as e:\n    if 'Lengths must match' in str(e):\n        raise ValueError(f\"align other to len {len(mask_arr)}\") from e\n    raise","preventionTips":["Always derive `other` from the same DataFrame column so lengths stay aligned.","Pass scalars (True/False/pd.NA) for broadcast comparisons rather than single-element lists.","Wrap logical ops in a helper that asserts len equality first."],"tags":["boolean-array","length-mismatch","logical-ops","valueerror"],"analyzedSha":"71959b8cb9b2459c16e14b34f28b178ccfe14735","analyzedAt":"2026-08-07T01:30:20.476Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}