pandas-dev/pandas · error · ValueError

Lengths of operands do not match: {len(self)} != {len(other)

Error message

Lengths of operands do not match: {len(self)} != {len(other)}

What it means

Raised by _str_arith_method_object_fallback when `other` is list-like and its length differs from len(self). This fallback path handles string arithmetic that pyarrow rejected (ArrowInvalid/TypeError) by operating elementwise in object dtype; it requires aligned lengths. The check at line 1264 enforces the contract before indexing with the validity mask.

Source

Thrown at pandas/core/arrays/arrow/array.py:1265

                f"'{op_name}' operations between boolean dtype and {self.dtype} are "
                "deprecated and will raise in a future version. Explicitly "
                "cast the strings to a boolean dtype before operating instead.",
                Pandas4Warning,
                stacklevel=find_stack_level(),
            )
            return op(other, self.astype(bool))
        else:
            return self._evaluate_op_method(other, op, ARROW_LOGICAL_FUNCS)

    def _str_arith_method_object_fallback(
        self, other, op
    ) -> Self | npt.NDArray[np.object_]:
        mask = isna(self) | isna(other)
        valid = ~mask

        if is_list_like(other):
            if len(other) != len(self):
                raise ValueError(
                    f"Lengths of operands do not match: {len(self)} != {len(other)}"
                )
            if not is_array_like_deprecate_non_pandas(other):
                other = np.asarray(other)
            other = other[valid]

        result = np.empty(len(self), dtype=object)
        result[mask] = self.dtype.na_value
        result[valid] = op(np.asarray(self, dtype=object)[valid], other)

        if not lib.is_string_array(result, skipna=True):
            return result
        return type(self)._from_sequence(result, dtype=self.dtype)

    def _arith_method(self, other, op) -> Self | npt.NDArray[np.object_]:
        if isinstance(other, BaseOffset) and pa.types.is_date(self._pa_array.type):
            # Cast date32/date64 → timestamp, apply offset via DatetimeArray, cast back
            ts_array = type(self)(self._pa_array.cast(pa.timestamp("us")))

View on GitHub (pinned to 71959b8cb9)

Solutions

  1. Align indexes/lengths before the op: reset_index or reindex to match.
  2. Broadcast a scalar instead of a list: s + sep (str), not s + [sep].
  3. Validate len(other) == len(s) up front.
  4. Use Series with aligned index so pandas handles broadcasting.

Example fix

# before
out = firsts + rests   # len 5 vs len 4 -> ValueError in fallback
# after
rests = rests.reindex(firsts.index)
out = firsts + rests
Defensive patterns

Strategy: validation

Validate before calling

def aligned_str_op(left, right, op):
    import numpy as np
    if hasattr(right, '__len__') and not isinstance(right, str):
        if len(right) != len(left):
            raise ValueError(f'length mismatch {len(left)} != {len(right)}')
    return op(left, right)

import operator
out = aligned_str_op(firsts, rests, operator.add)

Type guard

def is_length_aligned(other, target_len) -> bool:
    if isinstance(other, str) or not hasattr(other, '__len__'):
        return True  # scalar-like
    return len(other) == target_len

Try / catch

try:
    out = a + b
except ValueError as e:
    if 'Lengths of operands do not match' in str(e):
        # align via index or broadcast scalar
        out = a + pd.Series(b, index=a.index)
    else:
        raise

Prevention

When it happens

Trigger: String arithmetic fallback with mismatched lengths: `s1 + s2` where len(s1) != len(s2) and pyarrow already rejected the op so the object fallback runs. Also `s + [1,2]` against a length-3 string array.

Common situations: Concatenating columns from misaligned frames (different filters applied), broadcasting mistakes, or passing a short list expecting scalar broadcast (which the fallback does not do).

Related errors


AI-assisted analysis of pandas-dev/pandas@71959b8cb9 (2026-08-07). Data as JSON: /api/errors/b31eb84ac7c3142c. Report an issue: GitHub.