abs()
Returns the absolute value of a number, its distance from zero without a minus sign, useful for differences, distances and tolerances.
abs(x)abs() removes the minus sign: abs(-7) is 7, and abs(7) stays 7. Mathematicians call this the absolute value: how far a number is from zero.
It is most useful for differences when you do not care which value is bigger: how far apart two temperatures are, how much a budget was missed by, which number is closest to a target.
It works on any number type. For a complex number, it gives the length (magnitude): abs(3 + 4j) is 5.0.
Parameters
| Parameter | What it is |
|---|---|
xrequired | A number: int, float, complex, Decimal, Fraction, or any object that defines __abs__. |
Return value
A number of the same kind with no sign (for a complex number, a float).
Examples
1Basic use
print(abs(-7))
print(abs(7))
print(abs(-3.25))
print(abs(0))
print(abs(3 + 4j))7 7 3.25 0 5.0
2Difference between two values
berlin = -4
lisbon = 13
print("Temperature gap:", abs(berlin - lisbon), "degrees")
print("Same:", abs(lisbon - berlin), "degrees")Temperature gap: 17 degrees Same: 17 degrees
The order of subtraction no longer matters.
3How far off the budget?
budget = 500
for spent in [420, 515, 500]:
diff = spent - budget
if diff == 0:
print(spent, "exactly on budget")
else:
word = "over" if diff > 0 else "under"
print(spent, abs(diff), word)420 80 under 515 15 over 500 exactly on budget
4Find the closest value
sizes = [36, 38, 40, 42, 44]
wanted = 41.2
closest = min(sizes, key=lambda s: abs(s - wanted))
print(closest)42
min() with a key picks the size whose distance from wanted is smallest.
5Compare floats with a tolerance
a = 0.1 + 0.2
b = 0.3
print(a == b)
print(abs(a - b) < 1e-9)False True
Floats carry tiny errors, so check that the difference is very small instead of testing ==. math.isclose(a, b) does the same.
Common mistakes
Passing text
abs() needs a number. Convert strings from input or files first.
change = "-12.5"
try:
print(abs(change))
except TypeError:
print("TypeError: abs() needs a number, not a str")
print(abs(float(change)))TypeError: abs() needs a number, not a str 12.5
Using abs() to make a number negative
abs() always gives a positive result (or zero). For a guaranteed negative value write -abs(x).
print(-abs(8), -abs(-8))-8 -8
Questions people ask
How do I get the absolute value in Python?
abs(x). You do not need to import anything. math.fabs(x) also exists but always returns a float.
How do I find the difference between two numbers regardless of order?
abs(a - b).
Does abs() work on lists?
No. Apply it to each item: [abs(n) for n in numbers] or list(map(abs, numbers)).