# Distance Between Examples

Two examples become points when each feature is a direction, the straight-line (Euclidean) distance between them comes from the Pythagorean theorem and math.dist works it out for any number of features, and a feature measured in big units, like grams, swamps one scored from 0 to 10 until the features are put on a common scale.

Apprentice · AI Basics · Python · Updated November 19, 2026

By Gregor Dzierzon

## After this lesson you can

- Work out the straight-line distance between two examples by hand and with math.dist, and find the nearest of several examples
- Explain why a feature measured in big units swamps one measured from 0 to 10 in a distance, and why changing units can change the nearest example

## Key takeaways

- Each example is a point, one direction per feature, and two similar examples are close together.
- The straight-line distance squares each feature's difference, adds the squares and takes the square root. Your textbook calls it the Euclidean distance.
- math.dist(p, q) gives that distance for two points with any number of features.
- A feature with big numbers, such as grams, decides the distance almost alone. Change its units and the nearest example can change.

A fruit rolls off the belt at Three Rivers with no label, and you have hundreds of fruits that do have one. A natural guess: find the known fruit most like it, and call the new one the same. A music app suggesting songs like the ones you play, a store finding "customers like you" and a model that sorts fruit all start with the same question: how alike are two examples? Answer that with a number, and a computer can find the most alike. That number is a **distance**, and this lesson builds it by hand.

The example is Three Rivers' fruit, the measurements of `fruit.csv` from *Exercise: Fruit Sorter*. This lesson is plain Python.

## Two fruits as points

Take two features, sugar (in degrees Brix) and skin redness (0 to 10). Draw sugar across the bottom of a chart and redness up the side, and every fruit becomes a dot. A known apple with sugar 13.5 and redness 6.4 sits at the point (13.5, 6.4); the new fruit, 13.4 and 7.5, sits at (13.4, 7.5). Similar fruits are dots close together.

How close? Walk from one dot to the other: 0.1 across (sugar) and 1.1 up (redness). Those two walks and the straight line between the dots make a right triangle, and the **Pythagorean theorem** gives its long side: *a² + b² = c²*, read "a squared plus b squared equals c squared". Square each difference, add them, and take the square root. That straight-line length is the **Euclidean distance** (read "you-CLID-ee-un", after the Greek mathematician Euclid). Python's `math.dist` works it out for you:

```python
import math

known = (13.5, 6.4)
new_fruit = (13.4, 7.5)

across = new_fruit[0] - known[0]
up = new_fruit[1] - known[1]
print("By hand:", round(math.sqrt(across ** 2 + up ** 2), 2))
print("math.dist:", round(math.dist(new_fruit, known), 2))
```

```text
By hand: 1.1
math.dist: 1.1
```

Each point is a tuple, one number per feature, in the same order in both. A difference squared is never negative, so it doesn't matter which fruit you start from.

![A light chart with sugar in degrees Brix across the bottom from 11 to 15 and skin redness up the side from 0 to 10, with three labeled dots, a known apple at 13.5 and 6.4, the new fruit at 13.4 and 7.5 and a known pear at 11.4 and 2.9; a short straight line from the new fruit to the apple is marked 1.1, and a long one to the pear is the long side of a right triangle whose other sides are marked 2.0 across and 4.6 up, and is marked 5.02, so the apple is the nearer fruit](https://fsdtrainingmedia.blob.core.windows.net/public/images/2026/11/0c5421febd0e4af1ba636a9bdf0519a0.webp)

## Any number of features

A fruit has four measurements, so it's a point with four directions. Nobody can draw that, but the arithmetic doesn't change: square every feature's difference, add them all up, take the square root. `math.dist` takes points with any number of features. Here's the new fruit, 185 grams and 7.2 centimeters across, against one known fruit of each kind:

```python
import math

new_fruit = (185, 7.2, 13.4, 7.5)
known = {
    "an apple": (186, 8.1, 13.5, 6.4),
    "a pear": (201, 6.5, 11.4, 2.9),
    "a plum": (60, 4.8, 14.5, 8.1),
}
for name, measurements in known.items():
    print("To", name + ":", round(math.dist(new_fruit, measurements), 2))
```

```text
To an apple: 1.74
To a pear: 16.78
To a plum: 125.03
```

The apple is nearest, so the guess would be "apple". Finding the nearest known example is the whole idea behind *Nearest Neighbors*, the next lesson.

## When grams swamp the score

Look at what made the plum so far away: a 125-gram difference in weight, squared, is 15,625, while its biggest other difference, 2.4 centimeters, squared, is under 6. In a distance, a feature counts by the size of its numbers, not by how much it tells you. Grams run into the hundreds; redness never passes 10.

That can give the wrong answer. Use weight and redness only. The new fruit is 185 grams and bright red (7.5). A red apple weighs 179 grams; a green pear (redness 2.0) weighs exactly 185:

```python
import math

new_fruit = (185, 7.5)      # weight_g, skin_redness
red_apple = (179, 7.4)
green_pear = (185, 2.0)
print("Grams, to the apple:", round(math.dist(new_fruit, red_apple), 2))
print("Grams, to the pear:", round(math.dist(new_fruit, green_pear), 2))

new_fruit_kg = (0.185, 7.5)
print("Kilograms, to the apple:", round(math.dist(new_fruit_kg, (0.179, 7.4)), 2))
print("Kilograms, to the pear:", round(math.dist(new_fruit_kg, (0.185, 2.0)), 2))
```

```text
Grams, to the apple: 6.0
Grams, to the pear: 5.5
Kilograms, to the apple: 0.1
Kilograms, to the pear: 5.5
```

In grams, the green pear is "nearer": six grams of weight count for more than a whole color. Write the same weights in kilograms, and the apple is nearer, because now weight barely counts at all. Same fruits, same facts, a different answer, only because of the units someone chose. Neither answer is fair to both features. Putting every feature on a common scale, so that each counts by how unusual its value is rather than by its units, is called **feature scaling**, and *Scaling Features* in Module 4 shows how. Until then, remember that a distance is only as fair as its units.

## Do it: find the nearest known fruit

A new fruit comes off the line at Three Rivers, and you want the label of the known fruit most like it, using sugar and redness, two features with similar ranges.

The inputs:

- `fruits`: the known fruits' measurements, each a pair `(sugar_brix, skin_redness)`.
- `labels`: each known fruit's kind, in the same order.
- `new_fruit`: the new fruit's pair `(sugar_brix, skin_redness)`.

For example:

```python
fruits = [(13.5, 6.4), (11.4, 2.9), (14.5, 8.1)]
labels = ["apple", "pear", "plum"]
new_fruit = (13.4, 7.5)
```

| Known fruit | Label | Differences | Distance |
|---|---|---|---|
| (13.5, 6.4) | apple | 0.1 and 1.1 | 1.10 |
| (11.4, 2.9) | pear | 2.0 and 4.6 | 5.02 |
| (14.5, 8.1) | plum | 1.1 and 0.6 | 1.25 |

The apple is nearest, so `nearest_label(fruits, labels, new_fruit)` returns `"apple"`.

**Your job:** write `nearest_label(fruits, labels, new_fruit)`.

- It works out the straight-line distance from `new_fruit` to each known fruit (`math.dist` is fine).
- It returns the label of the nearest one.
- If two known fruits are equally near, it returns the label of the one that comes first in `fruits`.

Practiced live on the lesson page: write the Python right there and check it.

## Check yourself

2 questions to try on the lesson page.

## So what

A distance turns "how alike are these two?" into one number a computer can compare, but it weighs each feature by the size of its numbers, so a feature's units can quietly decide the answer.

## Sources

- Python documentation, [math.dist](https://docs.python.org/3/library/math.html#math.dist): the Euclidean distance between two points, each a sequence of coordinates of the same dimension, roughly `sqrt(sum((px - qx) ** 2.0 for px, qx in zip(p, q)))`; added in Python 3.8.
- scikit-learn 1.9.1, [KNeighborsClassifier](https://scikit-learn.org/stable/modules/generated/sklearn.neighbors.KNeighborsClassifier.html), API reference: the default metric, Minkowski with `p=2`, is the standard Euclidean distance.
- scikit-learn, [Importance of Feature Scaling](https://scikit-learn.org/stable/auto_examples/preprocessing/plot_scaling_importance.html), example: when one feature's values run from 0 to 1,000 and another's from 1 to 10, distances between samples are mostly decided by the first, and the second is comparatively ignored; scaled and unscaled data give k-nearest neighbors completely different models.

## Key terms

- [Euclidean Distance](https://www.ask-codey.com/glossary/euclidean-distance)
- [Pythagorean Theorem](https://www.ask-codey.com/glossary/pythagorean-theorem)
- [Feature](https://www.ask-codey.com/glossary/feature)
- [Feature Scaling](https://www.ask-codey.com/glossary/feature-scaling)

## Related

- [Nearest Neighbors](https://www.ask-codey.com/lessons/ml-nearest-neighbors)
- [Scaling Features](https://www.ask-codey.com/lessons/ml-scaling-features)
- [Exercise: Fruit Sorter](https://www.ask-codey.com/lessons/exercise-ml-fruit-sorter)

Source: https://www.ask-codey.com/lessons/ml-distance-between-examples
