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

StringArray._cmp_method performs element-wise comparison/arithmetic between self and a list-like `other`. Before operating it asserts len(other) == len(self); a mismatch raises ValueError showing both lengths. This prevents silent mis-broadcasting of 2-D or wrongly-sized operands.

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 71959b8cb9)

Solutions

  1. Match the operand length to the array length, or pass a scalar.
  2. Align via a pandas Series/Index so broadcasting is explicit.
  3. Broadcast manually: ['a'] * len(arr) if you want repetition.

Example fix

// before
string_array + ['a']

// after
string_array + 'a'
Defensive patterns

Strategy: validation

Validate before calling

import numpy as np
from pandas._libs import lib

if lib.is_list_like(other) and len(other) != len(string_array):
    other = other * (len(string_array) // len(other)) if len(other) == 1 else other
result = string_array + other

Type guard

def lengths_match(arr, other) -> bool:
    try:
        return len(other) == len(arr)
    except TypeError:
        return True  # scalar

Prevention

When it happens

Trigger: Calling string_array + ['a', 'b'] when lengths differ, string_array == other_array of a different length, or any element-wise op between a StringArray and a list/ndarray/ExtensionArray whose length does not match.

Common situations: Misaligned operands in vectorized ops; broadcasting a short list expecting repetition; comparing columns from different DataFrames without alignment.

Related errors


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