75
votes

Let's say I have x1, y1 and also x2, y2.

How can I find the distance between them? It's a simple math function, but is there a snippet of this online?

3
@Greg: His track record says no. @TIMEX: Searching didn't work? Seriously: google.com/search?q=python+distance+points - Glenn Maynard
-1 for "is there a snippet of this online?" Seriously, @TIMEX, if searching the web for a code snippet is too hard, now is the time for a change of career. - Johnsyweb
I'm surprised this question is closed. It was in my search results for 'python pythagoras' and was how I discovered the existence of math.hypot. - Rob Fisher
Okay, I just want to add a note that this is on the first page of google. It always frustrates me to see "just google it" as the first answer. Quite obviously there was some need that this question filled. - Dan
@GlennMaynard I came here by searching "python distance point", what do I do now? - melvinmt

3 Answers

120
votes
dist = sqrt( (x2 - x1)**2 + (y2 - y1)**2 )

As others have pointed out, you can also use the equivalent built-in math.hypot():

dist = math.hypot(x2 - x1, y2 - y1)
69
votes

Let's not forget math.hypot:

dist = math.hypot(x2-x1, y2-y1)

Here's hypot as part of a snippet to compute the length of a path defined by a list of (x, y) tuples:

from math import hypot

pts = [
    (10,10),
    (10,11),
    (20,11),
    (20,10),
    (10,10),
    ]

# Py2 syntax - no longer allowed in Py3
# ptdiff = lambda (p1,p2): (p1[0]-p2[0], p1[1]-p2[1])
ptdiff = lambda p1, p2: (p1[0]-p2[0], p1[1]-p2[1])

diffs = (ptdiff(p1, p2) for p1, p2 in zip (pts, pts[1:]))
path = sum(hypot(*d) for d in  diffs)
print(path)
18
votes

enter image description here It is an implementation of Pythagorean theorem. Link: http://en.wikipedia.org/wiki/Pythagorean_theorem