{"record":{"id":"eeb9c657b3290ee0","repo":"pandas-dev/pandas","slug":"lengths-must-match-eeb9c6","errorCode":null,"errorMessage":"Lengths must match","messagePattern":"Lengths must match","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"pandas/core/arrays/datetimelike.py","lineNumber":510,"sourceCode":"                # failed to parse as Timestamp/Timedelta/Period\n                raise InvalidComparison(other) from err\n\n        if isinstance(other, self._recognized_scalars) or other is NaT:\n            # error: Argument 1 to \"Timestamp\" has incompatible type \"object\";\n            # expected \"integer[Any] | float | str | date | datetime |\n            # datetime64[date | int | None]\"  [arg-type]\n            other = self._scalar_type(other)  # type: ignore[arg-type]\n            try:\n                self._check_compatible_with(other)\n            except TypeError as err:\n                # e.g. tzawareness mismatch\n                raise InvalidComparison(other) from err\n\n        elif not is_list_like(other):\n            raise InvalidComparison(other)\n\n        elif len(other) != len(self):\n            raise ValueError(\"Lengths must match\")\n\n        else:\n            try:\n                other = self._validate_listlike(other, allow_object=True)\n                self._check_compatible_with(other)\n            except TypeError as err:\n                if is_object_dtype(getattr(other, \"dtype\", None)):\n                    # We will have to operate element-wise\n                    pass\n                else:\n                    raise InvalidComparison(other) from err\n\n        return other\n\n    def _validate_scalar(\n        self,\n        value,\n        *,","sourceCodeStart":492,"sourceCodeEnd":528,"githubUrl":"https://github.com/pandas-dev/pandas/blob/71959b8cb9b2459c16e14b34f28b178ccfe14735/pandas/core/arrays/datetimelike.py#L492-L528","documentation":"Raised by DatetimeLikeArrayMixin._validate_comparison_value when comparing the array against a list-like whose length differs from the array's. Element-wise comparison requires equal lengths; broadcasting rules for datetime-like arrays do not auto-broadcast a mismatched-length list. This guard runs before the comparison so a clean ValueError is surfaced.","triggerScenarios":"datetime_array == [1,2,3] where the right side has a different length; Series of length N compared with a list of length M; comparison ops (<, >, ==, !=) between a datetime Series and a list/array/Index of mismatched length that is not a scalar.","commonSituations":"Passing a list derived from another column or a filtered subset without realigning the index; building a boolean mask from external data of the wrong length.","solutions":["Ensure both sides have the same length, or use a scalar for broadcasting.","Align via index: reindex or construct a Series with a matching index and let pandas align.","Validate len(other) == len(array) before the comparison."],"exampleFix":"// before\nts = pd.date_range('2020', periods=3)\nts == [pd.Timestamp('2020-01-01'), pd.Timestamp('2020-01-02')]  # ValueError\n\n// after\nts == [pd.Timestamp('2020-01-01')]*3  # broadcast scalar list of correct length","handlingStrategy":"validation","validationCode":"def compare_safe(arr, other):\n    import pandas as pd\n    if pd.api.types.is_list_like(other) and len(other) != len(arr):\n        raise ValueError(f'length {len(other)} != {len(arr)}')\n    return arr == other","typeGuard":"import pandas as pd\nfrom typing import Any\n\ndef lengths_match(a: Any, b: Any) -> bool:\n    if pd.api.types.is_list_like(b):\n        return len(a) == len(b)\n    return True","tryCatchPattern":"try:\n    arr == other\nexcept ValueError as e:\n    if 'Lengths must match' in str(e):\n        arr == [other[0]] * len(arr)\n    else:\n        raise","preventionTips":["Verify len(other) == len(arr) for list-like comparisons.","Use scalars for broadcasting, lists only for element-wise compare."],"tags":["datetime","comparison","length"],"analyzedSha":"71959b8cb9b2459c16e14b34f28b178ccfe14735","analyzedAt":"2026-08-07T01:30:20.476Z","schemaVersion":2},"datasetVersion":"2026-08-07T03:17:09.362Z"}