How can I find the distance between two points in Python?
Given two points with coordinates (x1, y1) and (x2, y2), what is the best way to calculate the distance between them? This is a simple mathematical operation, but is there a Python snippet available online to perform this calculation?
I’ve been working with Python for years, and the most basic way to calculate the distance between two points is to use the Euclidean distance formula manually. It’s simple and doesn’t require any extra libraries:
import math
def distance(x1, y1, x2, y2):
return math.sqrt((x2 - x1)**2 + (y2 - y1)**2)
# Example usage
x1, y1 = 1, 2
x2, y2 = 4, 6
print(distance(x1, y1, x2, y2)) # Output: 5.0
This approach is great if you’re looking for something lightweight and straightforward.
Shashank’s method works well, but if you’re working with larger datasets or need efficiency, you might want to use NumPy. It’s designed for numerical computations and makes operations like these faster and more concise.
import numpy as np
def distance(x1, y1, x2, y2):
return np.sqrt((x2 - x1)**2 + (y2 - y1)**2)
# Example usage
x1, y1 = 1, 2
x2, y2 = 4, 6
print(distance(x1, y1, x2, y2)) # Output: 5.0
With NumPy, you can even scale this up to handle arrays of points efficiently. It’s perfect for when you’re working with a lot of data.
Miro’s NumPy suggestion is fantastic for performance, but if you’re already using SciPy, there’s an even easier way to calculate distances. SciPy’s spatial.distance
module has a built-in function for Euclidean distance, making the code even cleaner:
from scipy.spatial import distance
def distance_points(x1, y1, x2, y2):
return distance.euclidean((x1, y1), (x2, y2))
# Example usage
x1, y1 = 1, 2
x2, y2 = 4, 6
print(distance_points(x1, y1, x2, y2)) # Output: 5.0
It’s the easiest way if you’re already using SciPy, and it supports other distance metrics as well.