Published on
· July 10, 2026

Euclidean Distance: What It Is, Formula, and Uses in Python

Blog
  • Photo of Henrico Piubello
    Henrico Piubello
    Henrico Piubello
    IT Specialist - Grupo Voitto

    IT Specialist - Grupo Voitto

Illustration of Euclidean distance applied to locating people by GPS

Euclidean distance is the measure of the shortest line segment between two points, calculated as the square root of the sum of the squared differences between the coordinates. In programming and data science, it quantifies the similarity between records and underpins algorithms like KNN and K-Means.

What is Euclidean distance?

Euclidean distance is a metric that measures the length of the line segment between two points in a Euclidean space — the shortest possible path between them. Derived from the Pythagorean theorem, it holds both for the two-dimensional plane and for spaces with any number of dimensions, which makes it the most used direct measure in geometry and data analysis.

The general formula for two points p and q with n dimensions is:

d(p, q) = √((q₁ - p₁)² + (q₂ - p₂)² + ... + (qₙ - pₙ)²)

For two points on a plane, (x₁, y₁) and (x₂, y₂), the expression reduces to √((x₂ - x₁)² + (y₂ - y₁)²). In programming practice, each point usually represents a data record — a user''s preferences, a product''s attributes — and the central rule of this metric holds: the smaller the Euclidean distance between two datasets, the greater the similarity between them.

What is the difference between Euclidean distance and other metrics?

Euclidean distance measures the straight-line path between two points, while metrics like Manhattan, cosine, and Hamming measure differences by axis, angle between vectors, or divergent positions. The choice depends on the data type and what the machine learning model needs to capture.

MetricHow it measuresTypical use
EuclideanStraight line between two pointsKNN, K-Means, continuous data
ManhattanSum of absolute differencesHigh dimensionality, outliers
CosineAngle between vectorsText and recommendation systems
MinkowskiGeneralizes Euclidean and ManhattanFine-tuning via parameter p
HammingDiffering positions between symbolsCategorical and binary data

An important caveat: Euclidean distance is sensitive to the scale of the variables. If one column ranges from 0 to 1 and another from 0 to 10,000, the second dominates the calculation. That is why normalizing or standardizing the data before measuring distances is a mandatory step in any serious analysis pipeline.

How to calculate Euclidean distance in Python?

In Python, Euclidean distance is calculated with the math.dist function from the standard library — available since Python 3.8, per the official documentation — or with numpy.linalg.norm for vectors of any dimension. To start from scratch, the recipe is simple:

  1. Import the math module (or NumPy, for multidimensional vectors).
  2. Define the two points as tuples or arrays of coordinates.
  3. Calculate the square root of the sum of the squared differences between the coordinates.
import math

def distancia_euclidiana(ponto1, ponto2):
    x1, y1 = ponto1
    x2, y2 = ponto2
    return math.sqrt((x2 - x1)**2 + (y2 - y1)**2)

distancia_euclidiana((1, 2), (4, 6))  # 5.0
math.dist((1, 2), (4, 6))  # equivalente na stdlib (Python 3.8+), 5.0

For multidimensional data, the numpy.linalg.norm function solves it in one line and in a vectorized way:

import numpy as np

a = np.array([1, 2])
b = np.array([4, 6])
np.linalg.norm(a - b)  # 5.0

If you are starting with the language, it is worth reviewing the beginner Python guide and the article on the NumPy library to master arrays before working with distance metrics.

Where is Euclidean distance used in machine learning?

Euclidean distance is the default similarity criterion of classic classification and clustering algorithms: KNN (K-Nearest Neighbors) classifies a new point by looking at its nearest neighbors, and K-Means groups observations by minimizing distances to centroids. In the official scikit-learn documentation, KNeighborsClassifier uses the Minkowski metric with p=2 by default — exactly Euclidean distance.

This reach is amplified by the size of the ecosystem. According to the Stack Overflow Developer Survey 2025, Python is used by 57.9% of developers, a jump of 7 percentage points in a year driven by AI (Artificial Intelligence) and data science. And the Python Developers Survey 2024, conducted by the PSF (Python Software Foundation) with JetBrains among more than 30,000 respondents, shows that 51% of Python developers work with data exploration and processing — the natural ground for distance metrics.

A concrete example: in a recommendation system, each user becomes a vector of preferences. By calculating the Euclidean distance between one user''s vector and everyone else''s, the system finds similar profiles and recommends items those profiles have already approved. To understand the broader context of these algorithms, see the machine learning fundamentals explained step by step.

When to use Euclidean distance in data science?

Use Euclidean distance when the variables are continuous, on the same scale (or normalized), and the number of dimensions is low or moderate. Under those conditions, it is the most intuitive and cheapest metric to compute for cluster analysis, anomaly detection, and similarity search.

In clustering analysis, calculating the Euclidean distance between points of a multidimensional set helps identify patterns and gather similar data. Imagine analyzing an e-commerce''s customers: the metric groups consumers with similar buying behavior, generating insights for personalized marketing strategies. In geospatial applications, like a program that estimates the shortest route between two points on a map using GPS (Global Positioning System) coordinates, Euclidean distance provides the baseline of the direct distance before considering streets and obstacles.

The limit appears in spaces with hundreds or thousands of dimensions: the distances between all points tend to equalize (curse of dimensionality) and the metric loses discriminative power. In those scenarios, reduce dimensions first or switch to Manhattan or cosine similarity, as the comparison table above summarizes.

Conclusion

Euclidean distance is one of those fundamentals that is worth more than it appears: a one-line formula, inherited from Pythagoras, underpins KNN, K-Means, recommendation, and cluster analysis. CodeCrush''s practical advice is direct — before adopting exotic metrics, normalize your data, start with Euclidean, and only switch metrics when the model results show it is not enough. Mastering this base makes any later study of similarity algorithms much faster.

## faq

Frequently asked questions

What is Euclidean distance used for in machine learning?

Euclidean distance measures the similarity between records: the smaller the distance, the more alike the data. KNN uses it to classify new points by their nearest neighbors, K-Means uses it to group observations into clusters, and recommendation systems apply it to compare user profiles and suggest items.

How to calculate Euclidean distance in Python?

Use math.dist(p, q) from the standard library, available since Python 3.8, or numpy.linalg.norm(a - b) for vectors of any dimension. Both functions return the square root of the sum of the squared differences between coordinates; the NumPy version is vectorized and faster for large data volumes.

Euclidean or Manhattan distance: which to choose?

Euclidean measures the straight-line path and is the default when the variables are continuous and on the same scale. Manhattan sums the absolute differences per axis and is usually more robust to outliers and high-dimensional data. Test both metrics and compare model performance.

When is Euclidean distance not a good choice?

Avoid Euclidean distance when the variables are on very different scales without normalization, when there are many dimensions (the so-called curse of dimensionality), or when direction matters more than magnitude, as in text vectors. In those cases, cosine similarity or Manhattan distance work better.

## continue lendo

Keep browsing

About the author

Photo of Henrico Piubello

Henrico Piubello

IT Specialist - Grupo Voitto · Grupo Voitto

See profile and all articles