How do I find the difference between two values without knowing which is larger?


I was wondering if there was a function built into Python that can determine the distance between two rational numbers but without me telling it which number is larger. e.g.


Obviously I could write a simple definition to calculate which is larger and then just do a simple subtraction:

def distance(x, y):
    if x >= y:
        result = x - y
        result = y - x
    return result

but I'd rather not have to call a custom function like this. From my limited experience I've often found Python has a built in function or a module that does exactly what you want and quicker than your code does it. Hopefully someone can tell me there is a built in function that can do this.

This question is tagged with python function numbers distance

~ Asked on 2012-11-28 09:47:48

The Best Answer is


abs(x-y) will do exactly what you're looking for:

In [1]: abs(1-2)
Out[1]: 1

In [2]: abs(2-1)
Out[2]: 1

~ Answered on 2012-11-28 09:49:13


Although abs(x - y) or equivalently abs(y - x) is preferred, if you are curious about a different answer, the following one-liners also work:

  • max(x - y, y - x)

  • -min(x - y, y - x)

  • max(x, y) - min(x, y)

  • (x - y) * math.copysign(1, x - y), or equivalently (d := x - y) * math.copysign(1, d) in Python =3.8

  • functools.reduce(operator.sub, sorted([x, y], reverse=True))

~ Answered on 2016-10-16 20:23:01

Most Viewed Questions: