{"record":{"id":"b15da83435fb383e","repo":"pandas-dev/pandas","slug":"lengths-of-operands-do-not-match-len-self-b15da8","errorCode":null,"errorMessage":"Lengths of operands do not match: {len(self)} != {len(other)}","messagePattern":"Lengths of operands do not match: (.+?) != (.+?)","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/string_.py","lineNumber":1250,"sourceCode":"\n        mask = isna(self) | isna(other)\n        valid = ~mask\n\n        if lib.is_list_like(other):\n            if not isinstance(\n                other, (list, ExtensionArray, np.ndarray)\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            if len(other) != len(self):\n                # prevent improper broadcasting when other is 2D\n                raise ValueError(\n                    f\"Lengths of operands do not match: {len(self)} != {len(other)}\"\n                )\n\n            # for array-likes, first filter out NAs before converting to numpy\n            if not is_array_like_deprecate_non_pandas(other):\n                other = np.asarray(other)\n            other = other[valid]\n\n        other_dtype = getattr(other, \"dtype\", None)\n        if op.__name__.strip(\"_\") in [\"mul\", \"rmul\"] and (\n            lib.is_bool(other) or lib.is_np_dtype(other_dtype, \"b\")\n        ):\n            # GH#62595\n            raise TypeError(\n                \"Cannot multiply StringArray by bools. \"\n                \"Explicitly cast to integers instead.\"\n            )\n","sourceCodeStart":1232,"sourceCodeEnd":1268,"githubUrl":"https://github.com/pandas-dev/pandas/blob/3b7651241d4da534b3559b60ef128e1c34f54116/pandas/core/arrays/string_.py#L1232-L1268","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Reindex or align operands so lengths match before the operation.","Use a scalar if you meant element-wise repetition: s + 'x'.","Construct a Series with a matching index so pandas can align: pd.Series(other, index=s.index).","Slice the longer operand to the same length explicitly."],"exampleFix":"// before\ns = pd.Series(['a','b','c'], dtype='string')\nresult = s + ['x','y']  # ValueError: 3 != 2\n// after\nresult = s + ['x','y','z']  # lengths match\n# or scalar\nresult = s + 'x'","handlingStrategy":"validation","validationCode":"def safe_binary_op(s, other, op):\n    other = pd.Series(other, index=s.index) if not pd.api.types.is_scalar(other) else other\n    if not pd.api.types.is_scalar(other) and len(other) != len(s):\n        raise ValueError(f\"Length mismatch: {len(other)} vs {len(s)}\")\n    return op(s, other)","typeGuard":"def operands_match_length(s, other) -> bool:\n    return pd.api.types.is_scalar(other) or len(other) == len(s)","tryCatchPattern":"try:\n    s + other\nexcept ValueError as e:\n    if 'Lengths of operands do not match' in str(e):\n        s + pd.Series(other, index=s.index)\n    else:\n        raise","preventionTips":["Align Series indices before element-wise ops.","Use scalars for true broadcasting.","Reindex operands to a common index."],"tags":["pandas","string-array","arithmetic","broadcasting","length-mismatch"],"backgroundTag":null,"analyzedSha":"3b7651241d4da534b3559b60ef128e1c34f54116","analyzedAt":"2026-08-11T22:10:44.015Z","contentChangedAt":null,"schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}