TheAlgorithms/Python · error · ValueError

Both points must have the same dimension.

Error message

Both points must have the same dimension.

What it means

Raised by minkowski_distance() in maths/minkowski_distance.py when point_a and point_b have different lengths. The distance is computed by zipping the two points term by term, which would silently truncate on length mismatch, so the function raises ValueError to enforce equal dimensionality.

Source

Thrown at maths/minkowski_distance.py:37

    >>> minkowski_distance([1.0, 2.0, 3.0, 4.0], [5.0, 6.0, 7.0, 8.0], 2)
    8.0
    >>> import numpy as np
    >>> bool(np.isclose(5.0, minkowski_distance([5.0], [0.0], 3)))
    True
    >>> minkowski_distance([1.0], [2.0], -1)
    Traceback (most recent call last):
        ...
    ValueError: The order must be greater than or equal to 1.
    >>> minkowski_distance([1.0], [1.0, 2.0], 1)
    Traceback (most recent call last):
        ...
    ValueError: Both points must have the same dimension.
    """
    if order < 1:
        raise ValueError("The order must be greater than or equal to 1.")

    if len(point_a) != len(point_b):
        raise ValueError("Both points must have the same dimension.")

    return sum(abs(a - b) ** order for a, b in zip(point_a, point_b)) ** (1 / order)


if __name__ == "__main__":
    import doctest

    doctest.testmod()

View on GitHub (pinned to f5988cc097)

Solutions

  1. Ensure both points have the same number of components before calling.
  2. Align vectors on a shared feature/column list, then extract values in the same order.
  3. Assert equal length at the point of construction so the bug surfaces near its cause.

Example fix

# before
minkowski_distance([1.0], [1.0, 2.0], 1)

# after
minkowski_distance([1.0, 0.0], [1.0, 2.0], 1)  # aligned dimensions
Defensive patterns

Strategy: validation

Validate before calling

if len(point_a) != len(point_b):
    raise ValueError(f'points differ in dimension: {len(point_a)} vs {len(point_b)}')

Prevention

When it happens

Trigger: minkowski_distance([1.0], [1.0, 2.0], 1) as in the doctest, or comparing any vectors of unequal length such as ([1,2,3], [1,2]).

Common situations: Feature vectors from different feature sets or schema versions, coordinates where one side carries an extra attribute, or lists built by independent filters.

Related errors


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