{"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":2004,"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":1986,"sourceCodeEnd":2022,"githubUrl":"https://github.com/pandas-dev/pandas/blob/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/arrays/sparse/array.py#L1986-L2022","documentation":"AssertionError from SparseArray._arith_method when operating element-wise against a list-like other whose length differs from self after np.asarray conversion. Lengths must match for sparse-sparse arithmetic; mismatch is treated as a programming error (hence AssertionError, not ValueError).","triggerScenarios":"arr + [1, 2, 3] when len(arr) != 3; arr * np.array(...) of a different length; broadcasting a Series whose index does not align.","commonSituations":"Assuming 1-element broadcasting for plain Python lists (pandas treats them as element-wise); index misalignment when one side is a Series; length bugs in upstream arrays.","solutions":["Broadcast explicitly with a scalar: arr * 2 instead of arr * [2].","Align lengths: ensure len(other) == len(arr) before the operation.","Operate through pd.Series to get index alignment: pd.Series(arr) + pd.Series(other, index=...)."],"exampleFix":"// before\narr + [1, 2, 3]  # raises if len(arr) != 3\n// after\narr + np.full(len(arr), 2)  # or simply arr + 2","handlingStrategy":"validation","validationCode":"import numpy as np\ndef aligned_binop(arr, other, op):\n    if hasattr(other, '__len__') and len(arr) != len(other):\n        raise ValueError(f'length {len(arr)} vs {len(other)}')\n    return op(arr, np.asarray(other))","typeGuard":"def lengths_match(arr, other) -> bool:\n    return not hasattr(other, '__len__') or len(arr) == len(other)","tryCatchPattern":"try:\n    arr + other\nexcept AssertionError as e:\n    if 'length mismatch' in str(e):\n        import numpy as np\n        other = np.broadcast_to(other, arr.shape) if np.isscalar(other) or len(other) == 1 else other\n        out = arr + other\n    else:\n        raise","preventionTips":["Use scalars for broadcasting; never 1-element lists.","Validate len(other) == len(arr) before arithmetic.","Operate through Series for index alignment."],"tags":["sparse","arithmetic","length-mismatch","broadcasting"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}