TheAlgorithms/Python · error · ValueError

x and y have different lengths

Error message

x and y have different lengths

What it means

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.

Solutions

  1. Re-align the arrays: filter x and y together, e.g. mask = ~np.isnan(y); x, y = x[mask], y[mask].
  2. Check for accidental slicing (x[:100] vs y[:99]) in the train/test split code.
  3. Assert len(x) == len(y) right after loading data to catch drift early.

Example fix

# before
dt.train(x, y[:-1])

# after
dt.train(x, y)  # or split both with the same indices: x[idx], y[idx]
Defensive patterns

Strategy: validation

Validate before calling

if len(x) != len(y):
    n = min(len(x), len(y))
    x, y = x[:n], y[:n]  # only if truncation is safe; otherwise raise
assert len(x) == len(y)
dt.train(x, y)

Type guard

def aligned_lengths(x, y) -> bool:
    return len(x) == len(y)

Try / catch

try:
    dt.train(x, y)
except ValueError as e:
    if "different lengths" in str(e):
        raise ValueError("features and labels out of sync; check NaN filtering") from e
    raise

Prevention

When it happens

Trigger: 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.

Common situations: 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.

Related errors


AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14). Data as JSON: /api/errors/6fe6c09cac393bcb. Report an issue: GitHub.

Appendix: source

Thrown at machine_learning/decision_tree.py:86

        >>> dt.train(np.array([1,2,3,4,5]),np.array([[0,0,0,1,1],[0,0,0,1,1]]))
        Traceback (most recent call last):
            ...
        ValueError: x and y have different lengths

        4. Try to train when x & y are of the same length but different dimensions
        >>> dt = DecisionTree()
        >>> dt.train(np.array([1,2,3,4,5]),np.array([[1],[2],[3],[4],[5]]))
        Traceback (most recent call last):
            ...
        ValueError: Data set labels must be one-dimensional

        This section is to check that the inputs conform to our dimensionality
        constraints
        """
        if x.ndim != 1:
            raise ValueError("Input data set must be one-dimensional")
        if len(x) != len(y):
            raise ValueError("x and y have different lengths")
        if y.ndim != 1:
            raise ValueError("Data set labels must be one-dimensional")

        if len(x) < 2 * self.min_leaf_size:
            self.prediction = np.mean(y)
            return

        if self.depth == 1:
            self.prediction = np.mean(y)
            return

        best_split = 0
        min_error = self.mean_squared_error(x, np.mean(y)) * 2

        """
        loop over all possible splits for the decision tree. find the best split.
        if no split exists that is less than 2 * error for the entire array
        then the data set is not split and the average for the entire array is used as

View on GitHub (pinned to f5988cc097)