Skip to content
Tutorials Center
My learning

Topics

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.

Python
abs(-7.5)        # 7.5
abs(3 + 4j)      # 5.0

Try it

Python Absolute values of different numbers

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.

Python abs() on your own class

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

Python
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") raises TypeError. Convert first with int() or float().
  • Negative zero. abs(-0.0) is 0.0.
  • Booleans are integers, so abs(True) is 1.
  • Complex numbers give the magnitude sqrt(real**2 + imag**2), a float. Use .real and .imag if you want the parts.
  • Differences. abs(a - b) is the usual way to measure how far apart two numbers are. For comparing floats, prefer math.isclose() over abs(a - b) < small, because it handles relative tolerance for you.
  • Use as a sort key. sorted(values, key=abs) orders by magnitude and max(values, key=abs) finds the value farthest from zero.
  • Overflow. Integers have no size limit, so abs() of an int never overflows (unlike fixed-width integers in C).
  • NumPy and pandas provide their own abs/np.abs for whole arrays; the built-in works on one value at a time.