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

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


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

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


Although abs(x - y) or equivalently abs(y - x) works, the following one-liners also work:

  • math.dist((x,), (y,)) (available in Python ≥3.8)

  • math.fabs(x - y)

  • 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))

All of these return the euclidean distance(x, y).


If you have an array, you can also use numpy.diff:

import numpy as npa = [1,5,6,8]np.diff(a)Out: array([4, 1, 2])