Python Reference ยท Built-in Functions
Python abs() function
Reference for Python abs(): absolute value of ints, floats, complex numbers, Fraction and Decimal, how it calls __abs__ on your own classes, and common mistakes.
The built-in abs() function returns the absolute value of a number: its distance from zero, without the sign. For an int or float that means negative numbers become positive and positive numbers stay as they are. For a complex number it returns the magnitude, which is always a float.
abs() also works on any object that defines the __abs__() special method, so Fraction, Decimal and your own classes (vectors, money types) can support it too.
abs(-7.5) # 7.5 abs(3 + 4j) # 5.0
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
abs(x)
| Name | Description |
|---|---|
x |
A number (int, float, complex, Fraction, Decimal, ...) or any object with an __abs__() method. Positional only. |
Return value: the absolute value. For int, float, Fraction and Decimal the result has the same type as the argument. For complex it is a float. For other objects it is whatever __abs__() returns.
Raises: TypeError if the object has no __abs__() method, for example a string or a list.
Usage notes
- Strings are not numbers.
abs("-5")raisesTypeError. Convert first withint()orfloat(). - Negative zero.
abs(-0.0)is0.0. - Booleans are integers, so
abs(True)is1. - Complex numbers give the magnitude
sqrt(real**2 + imag**2), a float. Use.realand.imagif you want the parts. - Differences.
abs(a - b)is the usual way to measure how far apart two numbers are. For comparing floats, prefermath.isclose()overabs(a - b) < small, because it handles relative tolerance for you. - Use as a sort key.
sorted(values, key=abs)orders by magnitude andmax(values, key=abs)finds the value farthest from zero. - Overflow. Integers have no size limit, so
abs()of anintnever overflows (unlike fixed-width integers in C). - NumPy and pandas provide their own
abs/np.absfor whole arrays; the built-in works on one value at a time.