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

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

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

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

Although abs(x - y) and equivalently abs(y - x) work, 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).


Just use abs(x - y). This'll return the net difference between the two as a positive value, regardless of which value is larger.