pandas-dev/pandas · error · ValueError

Lengths of operands do not match

Error message

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

What it means

The arithmetic/comparison path in StringArray raises ValueError when the right-hand operand is an array-like whose length differs from the array's, to block unintended 2D broadcasting or mismatched element-wise operations. After NAs are filtered, lengths must still match for vectorized ops.

Solutions

  1. Reindex or align operands so lengths match before the operation.
  2. Use a scalar if you meant element-wise repetition: s + 'x'.
  3. Construct a Series with a matching index so pandas can align: pd.Series(other, index=s.index).
  4. Slice the longer operand to the same length explicitly.

Example fix

// before
s = pd.Series(['a','b','c'], dtype='string')
result = s + ['x','y']  # ValueError: 3 != 2
// after
result = s + ['x','y','z']  # lengths match
# or scalar
result = s + 'x'
Defensive patterns

Strategy: validation

Validate before calling

def safe_binary_op(s, other, op):
    other = pd.Series(other, index=s.index) if not pd.api.types.is_scalar(other) else other
    if not pd.api.types.is_scalar(other) and len(other) != len(s):
        raise ValueError(f"Length mismatch: {len(other)} vs {len(s)}")
    return op(s, other)

Type guard

def operands_match_length(s, other) -> bool:
    return pd.api.types.is_scalar(other) or len(other) == len(s)

Try / catch

try:
    s + other
except ValueError as e:
    if 'Lengths of operands do not match' in str(e):
        s + pd.Series(other, index=s.index)
    else:
        raise

Prevention

When it happens

Trigger: Element-wise op between a string-dtyped Series and a list/np.ndarray of a different length: s + ['a','b'] where s has 3 elements; comparing s == another_series of different length.

Common situations: Broadcasting a scalar wrapped in a list by mistake; aligning two Series with mismatched indices that did not reindex; passing a column from a differently-filtered DataFrame.

Related errors


AI-assisted analysis of pandas-dev/pandas@3b7651241d (2026-08-11). Data as JSON: /api/errors/b15da83435fb383e. Report an issue: GitHub.

Appendix: source

Thrown at pandas/core/arrays/string_.py:1250

        mask = isna(self) | isna(other)
        valid = ~mask

        if lib.is_list_like(other):
            if not isinstance(
                other, (list, ExtensionArray, np.ndarray)
            ) 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(),
                )
            if len(other) != len(self):
                # prevent improper broadcasting when other is 2D
                raise ValueError(
                    f"Lengths of operands do not match: {len(self)} != {len(other)}"
                )

            # for array-likes, first filter out NAs before converting to numpy
            if not is_array_like_deprecate_non_pandas(other):
                other = np.asarray(other)
            other = other[valid]

        other_dtype = getattr(other, "dtype", None)
        if op.__name__.strip("_") in ["mul", "rmul"] and (
            lib.is_bool(other) or lib.is_np_dtype(other_dtype, "b")
        ):
            # GH#62595
            raise TypeError(
                "Cannot multiply StringArray by bools. "
                "Explicitly cast to integers instead."
            )

View on GitHub (pinned to 3b7651241d)