math.dist(p, q) returns the Euclidean distance between two points p and q, each given as a sequence or iterable of coordinates.
Added in Python 3.8, it works in any number of dimensions (2D, 3D, or higher) and uses math.hypot() internally so differences do not needlessly overflow.
math.dist() is a function in Python's standard math module: import it with import math and call math.dist(...), or import the name directly with from math import dist. Added in Python 3.8.
Syntax
Import math and pass two equal-length coordinate sequences (Python 3.8+).
python
import math
d = math.dist(point_a, point_b)
Call
What it does
math.dist((0, 0), (3, 4))
Returns 5.0.
math.dist([1, 2, 3], [3, 5, 9])
Returns 7.0 (3D distance).
math.dist([], [])
Returns 0.0.
math.dist([1, 2], [1, 2, 3])
Raises ValueError: dimension mismatch.
Both p and q must have the exact same length; use math.hypot() to measure distance from the origin.
Function signatures
python
math.dist(p, q, /)
# added in Python 3.8; p and q must have the same length
Parameters
Parameter
Description
p
Required iterable of numeric coordinates for the first point.
q
Required iterable of numeric coordinates for the second point, matching length of p.
Return Value
Return Value
Description
float
Euclidean distance sqrt(sum((px - qx) ** 2)).
Python Examples
Example 1 — Find the Nearest Delivery Waypoint on a 2D Grid
Measure grid distances and use min() with a key to pick the closest station.
3D integer triple. Coordinate gaps of 2, 3, and 6 square to 4 + 9 + 36 = 49, yielding exact 7.0.
Any iterable dimension. Four-element lists differ by 0.3 and 0.4 in the first two slots, giving 0.5.
Consistent float result. Every call returns a float regardless of whether inputs are lists or tuples.
Example 3 — Handle Dimension Mismatches and Empty Sequences
Catch ValueError when point lengths differ and inspect empty coordinate tuples.
python
import math
print("empty points:", math.dist((), ()))
try:
math.dist([1, 2], [1, 2, 3])
except ValueError:
print("points must have the same number of dimensions")
Output
empty points: 0.0
points must have the same number of dimensions
How It Works
Zero-dimensional space. Two empty tuples produce distance 0.0.
Strict length match. Comparing a 2D point to a 3D point raises ValueError instead of truncating like zip().
Fixed error handler. Catching ValueError lets your program validate user-supplied coordinates cleanly.
Frequently Asked Questions
math.dist() was added in Python 3.8.
Yes. It accepts points of any equal dimension, from 0D up to arbitrary lengths.
math.dist() raises ValueError instead of silently ignoring extra coordinates.
Yes. Any iterable of numbers works, including lists, tuples, and generators.
math.dist(p, q) computes the norm of the difference vector (p - q) using the same overflow-safe scaling as math.hypot().