Python abs() Function

Beginner
5 min read
Updated: Nov 2026
3 examples
Built-in

Definition

In Python, abs(x) returns the absolute value of x: how far the number is from zero, without its sign. abs(-7) is 7 and abs(7) is also 7.

For an int you get an int, for a float you get a float, and for a complex number you get its magnitude as a float. Any class can support abs() by defining a __abs__() method.

abs() is a built-in function: it lives in the builtins module, so it is always available without an import.

Syntax

Pass one number. The result is never negative.

python
distance = abs(x)
CallWhat it does
abs(-7)Returns 7 (an int).
abs(-2.5)Returns 2.5 (a float).
abs(3 + 4j)Returns 5.0, the magnitude of the complex number.
abs(a - b)Distance between two numbers, whichever is larger.

abs() takes exactly one positional argument; abs(x=5) is a TypeError.

Library declarations
python
abs(x, /)
# x: int, float, complex, or any object with __abs__()

Parameters

ParameterDescription
xRequired. A number (int, float, complex, Fraction, Decimal, ...) or an object that defines __abs__().

Return Value

Return ValueDescription
int / floatSame type as the argument for ints and floats (bool gives an int).
floatFor a complex number: its magnitude, sqrt(real**2 + imag**2).
anyWhatever the object's __abs__() returns.

Python Examples

Example 1 — Absolute Values of Mixed Numbers

Strip the sign from ints and floats in one loop and see that the type is kept.

python
readings = [-12, 7, -3.5, 0]

for value in readings:
    print(value, "->", abs(value))

How It Works

  1. Mixed list. readings holds negative and positive ints, a negative float, and zero.
  2. Sign removed. abs(-12) gives 12; values that are already positive come back unchanged.
  3. Type kept. -3.5 becomes the float 3.5, not an int, because abs() returns the same numeric type.
  4. Zero stays zero. Zero has no sign to remove, so abs(0) is 0.

Example 2 — Find the Guess Closest to a Target

Use abs(a - b) as a distance, both on its own and as a key for min().

python
target = 50
guesses = [42, 61, 47, 55]

for g in guesses:
    print(f"{g}: off by {abs(g - target)}")

closest = min(guesses, key=lambda g: abs(g - target))
print("Closest guess:", closest)

How It Works

  1. Distance, not difference. 42 - 50 is -8, but abs() turns it into a distance of 8.
  2. Direction ignored. Guesses above the target (61, 55) and below it (42, 47) are measured the same way.
  3. abs() as a key. min(..., key=lambda g: abs(g - target)) compares the distances but returns the original guess.
  4. Smallest distance wins. 47 is only 3 away, so it is printed as the closest guess.

Example 3 — Magnitude of a Complex Number and a Custom Class

See what abs() returns for complex numbers, how a class opts in with __abs__(), and what happens with a string.

python
class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __abs__(self):
        return (self.x ** 2 + self.y ** 2) ** 0.5


z = 3 + 4j
print(abs(z))
print(type(abs(z)).__name__)
print(abs(Vector(6, 8)))

try:
    abs("5")
except TypeError:
    print("abs() needs a number, not a str")

How It Works

  1. Complex magnitude. For 3 + 4j, abs() computes sqrt(3**2 + 4**2), which is 5.0.
  2. Always a float. The magnitude of a complex number is a real number, so type(abs(z)).__name__ is float.
  3. Opt in with __abs__. abs(Vector(6, 8)) calls Vector.__abs__, which returns the length 10.0.
  4. Strings are rejected. str has no __abs__, so abs("5") raises TypeError, which the except block reports.

Frequently Asked Questions

It returns the absolute value of a number, which is its distance from zero. abs(-4) and abs(4) both return 4.
It keeps the type for ints and floats: abs(-3) is 3 and abs(-3.0) is 3.0. For a complex number it always returns a float, the magnitude.
Convert it first: abs(int("-5")) returns 5. Passing the string directly raises TypeError.
math.fabs() always returns a float and does not accept complex numbers. abs() keeps ints as ints and also works on complex numbers and custom classes.
Yes. Define a __abs__(self) method that returns the value you want; abs(obj) will call it.

Next: aiter()

Get an asynchronous iterator (Python 3.10+).

aiter() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

7 people found this page helpful