{"record":{"id":"6fe6c09cac393bcb","repo":"TheAlgorithms/Python","slug":"x-and-y-have-different-lengths","errorCode":null,"errorMessage":"x and y have different lengths","messagePattern":"x and y have different lengths","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"machine_learning/decision_tree.py","lineNumber":86,"sourceCode":"        >>> dt.train(np.array([1,2,3,4,5]),np.array([[0,0,0,1,1],[0,0,0,1,1]]))\n        Traceback (most recent call last):\n            ...\n        ValueError: x and y have different lengths\n\n        4. Try to train when x & y are of the same length but different dimensions\n        >>> dt = DecisionTree()\n        >>> dt.train(np.array([1,2,3,4,5]),np.array([[1],[2],[3],[4],[5]]))\n        Traceback (most recent call last):\n            ...\n        ValueError: Data set labels must be one-dimensional\n\n        This section is to check that the inputs conform to our dimensionality\n        constraints\n        \"\"\"\n        if x.ndim != 1:\n            raise ValueError(\"Input data set must be one-dimensional\")\n        if len(x) != len(y):\n            raise ValueError(\"x and y have different lengths\")\n        if y.ndim != 1:\n            raise ValueError(\"Data set labels must be one-dimensional\")\n\n        if len(x) < 2 * self.min_leaf_size:\n            self.prediction = np.mean(y)\n            return\n\n        if self.depth == 1:\n            self.prediction = np.mean(y)\n            return\n\n        best_split = 0\n        min_error = self.mean_squared_error(x, np.mean(y)) * 2\n\n        \"\"\"\n        loop over all possible splits for the decision tree. find the best split.\n        if no split exists that is less than 2 * error for the entire array\n        then the data set is not split and the average for the entire array is used as","sourceCodeStart":68,"sourceCodeEnd":104,"githubUrl":"https://github.com/TheAlgorithms/Python/blob/f5988cc09713315817df6a7e327e258013a94440/machine_learning/decision_tree.py#L68-L104","documentation":"Raised by DecisionTree.train when len(x) != len(y). Every training sample needs exactly one label; mismatched lengths mean samples are unlabeled or orphan labels exist, so training is refused before any split search.","triggerScenarios":"Calling dt.train(x, y) where x and y come from different slices, e.g. x = all rows but y = y[:-1], or labels shuffled/filtered independently of features.","commonSituations":"Off-by-one in manual train/test slicing, dropping NaN labels without dropping the matching x rows, or merging features and labels from sources that got out of sync.","solutions":["Re-align the arrays: filter x and y together, e.g. mask = ~np.isnan(y); x, y = x[mask], y[mask].","Check for accidental slicing (x[:100] vs y[:99]) in the train/test split code.","Assert len(x) == len(y) right after loading data to catch drift early."],"exampleFix":"# before\ndt.train(x, y[:-1])\n\n# after\ndt.train(x, y)  # or split both with the same indices: x[idx], y[idx]","handlingStrategy":"validation","validationCode":"if len(x) != len(y):\n    n = min(len(x), len(y))\n    x, y = x[:n], y[:n]  # only if truncation is safe; otherwise raise\nassert len(x) == len(y)\ndt.train(x, y)","typeGuard":"def aligned_lengths(x, y) -> bool:\n    return len(x) == len(y)","tryCatchPattern":"try:\n    dt.train(x, y)\nexcept ValueError as e:\n    if \"different lengths\" in str(e):\n        raise ValueError(\"features and labels out of sync; check NaN filtering\") from e\n    raise","preventionTips":["Filter x and y with the same boolean mask.","Slice train/test sets with shared indices.","Assert len equality immediately after loading."],"tags":["machine-learning","decision-tree","data-alignment","input-validation"],"backgroundTag":null,"analyzedSha":"f5988cc09713315817df6a7e327e258013a94440","analyzedAt":"2026-08-14T17:30:07.041Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}