pandas-dev/pandas · error · AssertionError
length mismatch: vs.
Error message
length mismatch: {len(self)} vs. {len(other)} What it means
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).
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=...).
Example fix
// before arr + [1, 2, 3] # raises if len(arr) != 3 // after arr + np.full(len(arr), 2) # or simply arr + 2
Defensive patterns
Strategy: validation
Validate before calling
import numpy as np
def aligned_binop(arr, other, op):
if hasattr(other, '__len__') and len(arr) != len(other):
raise ValueError(f'length {len(arr)} vs {len(other)}')
return op(arr, np.asarray(other)) Type guard
def lengths_match(arr, other) -> bool:
return not hasattr(other, '__len__') or len(arr) == len(other) Try / catch
try:
arr + other
except AssertionError as e:
if 'length mismatch' in str(e):
import numpy as np
other = np.broadcast_to(other, arr.shape) if np.isscalar(other) or len(other) == 1 else other
out = arr + other
else:
raise Prevention
- Use scalars for broadcasting; never 1-element lists.
- Validate len(other) == len(arr) before arithmetic.
- Operate through Series for index alignment.
When it happens
Trigger: arr + [1, 2, 3] when len(arr) != 3; arr * np.array(...) of a different length; broadcasting a Series whose index does not align.
Common situations: 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.
Related errors
- Lengths of operands do not match
- can only perform ops with 1-d structures
- Lengths must match
- Lengths of operands do not match
- operands have mismatched length
AI-assisted analysis of pandas-dev/pandas@3b7651241d (2026-08-11).
Data as JSON: /api/errors/7a333fc7190fc73f.
Report an issue: GitHub.
Appendix: source
Thrown at pandas/core/arrays/sparse/array.py:2004
return _wrap_result(op_name, result, self.sp_index, fill)
else:
if not isinstance(
other, (list, np.ndarray, ExtensionArray)
) and not ops.has_castable_attr(other):
warnings.warn(
f"Operation with {type(other).__name__} is deprecated. "
"In a future version these will be treated as scalar-like. "
"To retain the old behavior, explicitly wrap in a Series "
"instead.",
Pandas4Warning,
stacklevel=find_stack_level(),
)
other = np.asarray(other)
with np.errstate(all="ignore"):
if len(self) != len(other):
raise AssertionError(
f"length mismatch: {len(self)} vs. {len(other)}"
)
if not isinstance(other, SparseArray):
dtype = getattr(other, "dtype", None)
other = SparseArray(other, fill_value=self.fill_value, dtype=dtype)
return _sparse_array_op(self, other, op, op_name)
def _cmp_method(self, other, op) -> SparseArray:
if (
is_list_like(other)
and not isinstance(other, (list, np.ndarray, ExtensionArray))
and not ops.has_castable_attr(other)
):
warnings.warn(
f"Operation with {type(other).__name__} is deprecated. "
"In a future version these will be treated as scalar-like. "
"To retain the old behavior, explicitly wrap in a Series "
"instead.",View on GitHub (pinned to 3b7651241d)