{"record":{"id":"7a333fc7190fc73f","repo":"pandas-dev/pandas","slug":"length-mismatch-len-self-vs-len-other","errorCode":null,"errorMessage":"length mismatch: {len(self)} vs. {len(other)}","messagePattern":"length mismatch: (.+?) vs\\. (.+?)","errorType":"exception","errorClass":"AssertionError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/sparse/array.py","lineNumber":1970,"sourceCode":"            return _wrap_result(op_name, result, self.sp_index, fill)\n\n        else:\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\n            other = np.asarray(other)\n            with np.errstate(all=\"ignore\"):\n                if len(self) != len(other):\n                    raise AssertionError(\n                        f\"length mismatch: {len(self)} vs. {len(other)}\"\n                    )\n                if not isinstance(other, SparseArray):\n                    dtype = getattr(other, \"dtype\", None)\n                    other = SparseArray(other, fill_value=self.fill_value, dtype=dtype)\n                return _sparse_array_op(self, other, op, op_name)\n\n    def _cmp_method(self, other, op) -> SparseArray:\n        if (\n            is_list_like(other)\n            and not isinstance(other, (list, np.ndarray, ExtensionArray))\n            and not ops.has_castable_attr(other)\n        ):\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.\",","sourceCodeStart":1952,"sourceCodeEnd":1988,"githubUrl":"https://github.com/pandas-dev/pandas/blob/71959b8cb9b2459c16e14b34f28b178ccfe14735/pandas/core/arrays/sparse/array.py#L1952-L1988","documentation":"Raised (as AssertionError) by SparseArray._arith_method when a non-scalar, non-SparseArray operand is converted to ndarray and its length differs from len(self). Sparse arithmetic requires element-wise alignment; mismatched lengths can't be broadcast and the operation is rejected before the sparse kernel is invoked.","triggerScenarios":"sparse_arr + np.array([1,2,3]) of different length, sparse_arr * list_of_wrong_length, or arithmetic between two Series whose indexes were silently reindexed to different lengths.","commonSituations":"Broadcasting mistakes (assuming a column vector aligns with a row), stale cached lengths, or operating on filtered sublists without re-aligning indexes.","solutions":["Align lengths explicitly: other = np.asarray(other); assert len(other) == len(sparse_arr).","Use Series arithmetic which aligns on index instead of position: pd.Series(sparse_arr) + pd.Series(other).","If the operand is meant to be scalar, pass a scalar (int/float) instead of a 1-element list."],"exampleFix":"// before\nout = sparse_arr + np.array([1, 2])  # raises if len(sparse_arr) != 2\n\n// after\nout = pd.Series(sparse_arr) + pd.Series(np.array([1, 2]), index=...)  # index-aligned","handlingStrategy":"validation","validationCode":"import numpy as np\n\ndef arith_sparse_safe(arr, other):\n    other_arr = np.asarray(other)\n    if other_arr.ndim == 1 and len(other_arr) != len(arr):\n        raise ValueError(f'length {len(other_arr)} != {len(arr)}')\n    return arr + other_arr","typeGuard":"import numpy as np\n\ndef lengths_match(arr, other) -> bool:\n    o = np.asarray(other)\n    return o.ndim == 0 or len(o) == len(arr)","tryCatchPattern":"try:\n    out = sparse_arr + other\nexcept AssertionError as e:\n    if 'length mismatch' in str(e):\n        # align via Series instead\n        out = (pd.Series(sparse_arr) + pd.Series(other)).array\n    else:\n        raise","preventionTips":["Use Series arithmetic to get index alignment instead of positional ops","Validate len(other) == len(arr) before element-wise ops on .array","Pass scalars (not 1-element lists) when broadcasting"],"tags":["sparse","arithmetic","length-mismatch","alignment"],"analyzedSha":"71959b8cb9b2459c16e14b34f28b178ccfe14735","analyzedAt":"2026-08-07T01:30:20.476Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}