🚀 Supercharge your YouTube channel's growth with AI.
Try YTGrowAI FreeHow to Calculate Distance Between Two Points in Python

Comparing two coordinate points starts with choosing what kind of distance the calculation should represent. In Python, math.dist measures straight-line Euclidean distance for points with matching dimensions.
This article demonstrates the calculation and checks it against a manual result. It also shows when array libraries or a different distance measure fit the task.
TL;DR: Calculate distance with math.dist
Use Python’s math.dist(point_a, point_b) for straight-line Euclidean distance between coordinate sequences with matching dimensions.
- Use Euclidean distance for straight-line coordinate separation.
- Use Manhattan distance to sum axis-by-axis movement.
- Use Hamming distance to count differing positions in equal-length sequences.
- Use a geographic formula or library for latitude and longitude, not a flat-plane shortcut.
What is distance between two points?
In coordinate geometry, a point is an ordered set of values such as (x, y) on a plane or (x, y, z) in space.
Python lists and tuples can store these coordinates in order.
For points on a plane, this is the length of the straight segment joining them.
How to calculate distance step by step
Start with two coordinate sequences, then apply the formula matching the task.
Step 1: Choose points with matching coordinates
Use (1, 2, 3) and (4, 6, 3) as sample points.
Convert meters and feet before comparing them because the function cannot infer units.
Step 2: Calculate Euclidean, Manhattan, and Hamming values
Run this dependency-free example with Python 3.8 or later, which provides math.dist. The points are chosen so the coordinate differences are 3, 4, and 0.
from math import dist
point_a = (1, 2, 3)
point_b = (4, 6, 3)
print(f"Euclidean: {dist(point_a, point_b):.4f}")
print(f"Manhattan: {sum(abs(a - b) for a, b in zip(point_a, point_b))}")
print(f"Hamming: {sum(a != b for a, b in zip(point_a, point_b))}")
The output from the command python3 distance_demo.py is shown here.
Euclidean: 5.0000
Manhattan: 7
Hamming: 2

The three outputs separate geometric distance from axis movement and unequal-position counts.
Step 3: Check the formula against a manual calculation
Run python3 distance_checks.py to compare the formulas and see the dimensions check.
math.dist: 5.0000
manual: 5.0000
dimension error: both points must have the same number of dimensions

The output shows both calculations return 5.0000, followed by the mismatch error.
For points measured from the origin, math.hypot(x, y) gives the norm directly.
Step 4: Use a library for arrays or collections
When your data already uses NumPy arrays, subtract one point array from the other and pass the result to numpy.linalg.norm. Its default is the 2-norm for this one-dimensional vector.
import numpy as np
point_a = np.array([1, 2, 3])
point_b = np.array([4, 6, 3])
euclidean = np.linalg.norm(point_a - point_b)
manhattan = np.linalg.norm(point_a - point_b, ord=1)
This snippet computes values without printing an output, so it can be included in a larger NumPy calculation. If you need a printed result, run the complete example from a named script. Avoid converting to arrays solely to calculate one pair when math.dist already fits the job.
Use scipy.spatial.distance.cdist for pairwise comparisons between two collections.
For graph nodes where distance means traversing edges, see calculating distance between nodes in an unweighted graph.
Implement the calculation with a loop
A direct implementation makes each calculation step explicit. I use it here to show where the input check belongs.
from math import sqrt
def euclidean_distance(point_a, point_b):
if len(point_a) != len(point_b):
raise ValueError("points must have matching dimensions")
squared_total = 0
for coordinate_a, coordinate_b in zip(point_a, point_b):
difference = coordinate_a - coordinate_b
squared_total += difference * difference
return sqrt(squared_total)
print(euclidean_distance((1, 2, 3), (4, 6, 3)))
The loop accumulates squared differences, then takes one square root. Its length check prevents zip from dropping a trailing coordinate.
Implement distance calculations for a collection
A collection changes the shape of the problem. Compare each item to a reference, within one group, or across two groups.
For a reference point and a short Python list, a comprehension is clear. Each result stays aligned with the input point that produced it:
from math import dist
origin = (0, 0)
points = [(3, 4), (5, 12), (8, 15)]
distances = [dist(origin, point) for point in points]
print(distances)
This one-to-many result has one number per input point. For two larger collections, SciPy’s cdist returns a rectangular matrix. A square pairwise matrix compares each observation with every other one, but its storage grows with the product of the collection sizes.
Choose inputs and output precision deliberately
Coordinates may be integers or floating-point values, and the calculated distance is typically floating point. Keep the unrounded result for later calculations and format it only when displaying it.
Fixed-decimal formatting changes the displayed text, not the underlying value. This matters when ranking candidate points: rounding first can make two different distances look tied.
Missing values require a deliberate policy. None cannot be subtracted from a number, while NaN can propagate through arithmetic and produce a result that is not useful for comparison.
Integer coordinates may be very large, while floating-point values have finite precision. For ordinary geometric work, Python’s built-in arithmetic is appropriate. For applications where exact arithmetic matters, such as rational grid calculations, keep values as fractions through the squared-sum stage and consider whether the final square root can be represented exactly.
When saving results, record the metric and any scaling so the value can be interpreted later.
Choose the right distance and handle edge cases
These cases need different interpretations and Python operations.
I checked math.dist((1, 2), (3, 4, 5)) and got ValueError: “both points must have the same number of dimensions”. Reject mismatched points before calculating.
| Input and goal | Metric | Python choice |
|---|---|---|
| Numeric coordinates, straight line | Euclidean | math.dist(a, b) |
| Movement only along grid axes | Manhattan | Sum abs(a[i] – b[i]) |
| Equal-length symbols or categories | Hamming | Count unequal positions |
| Many observations in arrays | Selected pairwise metric | SciPy cdist or pdist |
| Latitude and longitude | Geodesic or spherical | Use a geographic method |
A degree of longitude covers different ground distances at different latitudes, so choose a geographic method that fits the required precision and coordinate datum.
In machine-learning data, standardization or normalization can stop a large-valued feature from dominating. The transformation changes the geometry, so apply the same documented scaling to future points.
Negative coordinates work because the formula squares each difference, and equal points produce zero.
If one feature is measured in meters and another in seconds, a direct Euclidean result combines unlike units. Convert or define a domain-based scaling rule first.
For (0, 0) and (3, 4), Euclidean and Manhattan distance return 5 and 7. Neither models obstacles along a route.
For geographic coordinates, see the Haversine formula for calculating GPS distances. It covers the Earth-surface interpretation that a flat coordinate formula does not provide.
SciPy’s hamming function returns the proportion of differing components, so multiply by sequence length when you need a count.
For two empty sequences, a raw mismatch count is zero, while a normalized fraction would divide by zero. Define which convention your application accepts.
Code implementation: choose a formula for the job
The coordinate formula is the same across dimensions: subtract corresponding coordinates, square each difference, add the squares, and take the square root. In two dimensions, the familiar expression is sqrt((x2 – x1)^2 + (y2 – y1)^2).
Points in three dimensions add a squared z difference, and higher dimensions follow the same rule.
For a normal pair of points in Python 3.8 or later, math.dist communicates this intent directly. It accepts coordinate iterables, including tuples and lists, as long as both contain the same number of coordinates.
A point can therefore have two, three, or more dimensions. Keep coordinate order consistent: comparing (x, y) with (latitude, longitude) is only meaningful if both sequences describe the same axes in the same order.
If an older Python version is required, the loop shown above reproduces the definition using sqrt. Its explicit length check is important because zip stops as soon as either input ends. Without the check, a custom implementation could silently ignore an extra coordinate rather than report that the points are incompatible.
For two-dimensional points, math.hypot(x2 – x1, y2 – y1) is another standard-library choice. It computes the Euclidean norm of the supplied values.
Pass every coordinate difference for higher dimensions. Passing both points’ raw coordinates instead measures their norms from the origin, not their separation.
Apply the formula to multiple points
When one reference point is compared with a short list, a comprehension keeps the calculation compact and preserves the list’s order. Each output belongs to the point at the same index. This is useful when the next operation is to label, display, or sort those individual distances.
For larger numerical datasets, NumPy represents coordinates as arrays. Subtracting one point array from another produces a vector of coordinate differences, and numpy.linalg.norm calculates its norm.
The default vector norm is the 2-norm, which corresponds to Euclidean length. The ord=1 option instead adds the absolute coordinate differences, a Manhattan calculation.
Make sure the arrays represent points with compatible shapes and that the chosen axis is the coordinate axis if the data contains batches.
There is a practical reason not to convert a single tuple just to call NumPy: the extra dependency and array conversion do not add value for one pair. NumPy becomes useful when the data is already in arrays or when a workflow applies vector operations to many rows. The representation should follow the surrounding computation rather than dictate it.
For comparisons across two collections, SciPy provides cdist, which forms a distance matrix. If collection A has m points and collection B has n points, the result has m rows and n columns.
Entry [i, j] represents the selected metric between A[i] and B[j]. Use the metric argument to state the distance definition, and confirm that each row is one observation with the same coordinate count.
This all-pairs result can use substantial memory as both collections grow, so avoid constructing the full matrix if the application needs only a small subset of pairs.
For distances among points in one collection, SciPy’s pdist stores unique pairwise distances in condensed form rather than a full square matrix, omitting mirrored pairs and diagonal zeroes.
It is useful for clustering-oriented tasks, but it is not interchangeable with a rectangular cross-collection result. Choose the shape expected by later code before selecting the function.
Metric choice also changes meaning, not just implementation. Euclidean distance is direct straight-line separation.
Manhattan distance counts movement along coordinate axes, which can better model a rectangular grid. Hamming distance compares corresponding entries and counts which ones differ. For strings or categories, entries need not be numeric coordinates.
These values should not be compared as if they answered the same question.
Interpret the result and its limits
The output uses the same units as the input when every coordinate uses one consistent unit. If points are measured in meters, the Euclidean result is in meters.
Convert coordinates first when one axis is in meters and another is in centimeters. The raw numerical result would have no coherent physical unit.
Feature scaling matters in data analysis because a dimension with large numeric values can dominate a Euclidean calculation, even when that dimension is not more important.
Standardizing or normalizing features changes the geometry and therefore changes what a “near” point means. Apply the same transformation to both points and to later query points, and keep the fitted scaling parameters with the model or process that produced them.
Finally, straight-line coordinate distance is not automatically travel distance. A route can be longer because roads, walls, or other constraints prevent direct movement.
Latitude and longitude introduce a different issue because degree coordinates are angular positions on Earth rather than a flat Cartesian plane. Use a geographic calculation for locations, and use a graph path algorithm when distance means the cost of traversing edges.
Conclusion
For a single numeric point pair, math.dist is the concise Euclidean choice.
Read the official Python math documentation for dist and hypot, and the NumPy norm reference for array calculations. For graph path length, see distance between nodes in an unweighted graph.
FAQ
These quick answers cover common variations of the point-distance calculation.
How do I calculate distance between two points in Python without NumPy?
Use math.dist(point_a, point_b) in Python 3.8 or later. It returns Euclidean distance for coordinate sequences with equal dimensions.
Can math.dist calculate distance in three dimensions?
Yes. Give each point three coordinates in the same order. math.dist supports coordinate iterables in any matching dimension.
How do I calculate Manhattan distance in Python?
Add the absolute difference for each corresponding coordinate. This is the axis-aligned or city-block distance.
Does Euclidean distance work for latitude and longitude?
Raw degree coordinates are not a suitable flat-plane measurement for general locations. Use a geodesic or spherical method designed for geographic coordinates.


