To get the absolute value in Python, call the built-in abs(): abs(-7) returns 7 and abs(-2.5) returns 2.5. It works on integers, floats and complex numbers without any import.
print(abs(-7)) # 7
print(abs(-2.5)) # 2.5
print(abs(4)) # 4
print(abs(-0.0)) # 0.0
That is example output you can reproduce in any Python 3 interpreter. The rest of this article covers what abs() accepts, how it differs from math.fabs(), how to apply it to lists and arrays, and the cases that surprise people.
What abs() does
The Python documentation describes abs(number, /) in one sentence: it returns the absolute value of a number, and the argument may be an integer, a floating-point number, or an object implementing __abs__(). If the argument is a complex number, its magnitude is returned. The / in the signature means the argument is positional-only, so abs(number=-3) raises a TypeError. Write abs(-3).
The absolute value of a real number is its distance from zero, so the sign is dropped and the size is kept. Positive numbers and zero come back unchanged. Negative numbers come back as their positive counterpart.
The return type follows the input. An int in gives an int out, and a float in gives a float out:
print(type(abs(-7))) # <class 'int'>
print(type(abs(-7.0))) # <class 'float'>
Because abs() is a plain function, you can use it anywhere an expression is allowed: in comparisons, in arithmetic, or as a key argument to sorted().
Absolute value of a complex number
For a complex number a + bj, abs() returns the magnitude, which is the square root of a**2 + b**2. The result is a float, even when it happens to be a whole number:
print(abs(3 + 4j)) # 5.0
print(abs(-3 - 4j)) # 5.0
This is the same calculation as the distance formula, which is why math.hypot(3, 4) also gives 5.0. The math documentation describes hypot as the Euclidean norm, the length of the vector from the origin to the given point. Both are fine for two numbers. If you already hold a complex value, abs() is shorter.
abs() versus math.fabs()
The math module has its own function, math.fabs(x), which the documentation describes as returning the absolute value of x. The practical differences are:
abs(x) | math.fabs(x) | |
|---|---|---|
| Needs an import | No, it is a built-in | Yes, import math |
| Integer input | Returns an int | Returns a float |
| Float input | Returns a float | Returns a float |
| Complex input | Returns the magnitude | Raises TypeError |
| Custom types | Works if the type defines __abs__() | Needs something convertible to a float |
import math
print(abs(-7)) # 7
print(math.fabs(-7)) # 7.0
Use abs() unless you specifically want a float back. A large integer is one reason to prefer it: math.fabs() converts to a float first, and very large integers cannot always be represented exactly as floats, while abs() keeps the integer exact.
Absolute value of every item in a list
abs() takes one number, not a list, so abs([-1, -2]) raises TypeError: bad operand type for abs(): 'list'. Apply it to each item instead. A list comprehension is the usual choice:
numbers = [-3, 4, -1.5, 0]
absolute_values = [abs(value) for value in numbers]
print(absolute_values) # [3, 4, 1.5, 0]
map() does the same thing lazily. Wrap it in list() if you need a list:
print(list(map(abs, numbers))) # [3, 4, 1.5, 0]
To sum absolute values, pass a generator to sum(): sum(abs(value) for value in numbers) gives 8.5 here. If you want the largest value by size while keeping its original sign, use the key argument: max(numbers, key=abs) returns 4, and min(numbers, key=abs) returns 0.
Absolute value in NumPy and pandas
For arrays, use NumPy. numpy.absolute() computes the absolute value element by element, and the NumPy documentation states that np.abs is a shorthand for it. The built-in abs() also works on arrays:
import numpy as np
values = np.array([-1.2, 1.2, -3.0])
print(np.abs(values)) # [1.2 1.2 3. ]
print(abs(values)) # [1.2 1.2 3. ]
For a complex input a + ib the result is the real value sqrt(a**2 + b**2), matching the built-in behaviour. The result is a scalar if the input is a scalar. A NumPy array is much faster than a Python loop for large amounts of numbers, because the loop runs in compiled code. A pandas Series and DataFrame have an .abs() method for the same purpose.
Use abs() to compare numbers with a tolerance
A common real use is checking whether two floats are close enough. Floats store most decimal fractions approximately, so an exact == comparison can fail:
print(0.1 + 0.2 == 0.3) # False
print(abs((0.1 + 0.2) - 0.3) < 1e-9) # True
The difference between the two values can be positive or negative depending on which is larger, so abs() turns it into a distance you can compare against a tolerance. For production code, the standard library already has math.isclose(a, b) for this job, which handles relative tolerance as well. The first article below explains why the sum above is not exactly 0.3.
Another frequent use is distance on a number line, such as the gap between two scores or timestamps: abs(score_a - score_b) is the same no matter which score is larger.
Custom classes and __abs__()
The documentation says abs() accepts any object that implements __abs__(). That is how standard library types such as fractions.Fraction and decimal.Decimal support it, and you can add it to your own class:
import math
class Vector:
def __init__(self, x: float, y: float) -> None:
self.x = x
self.y = y
def __abs__(self) -> float:
return math.hypot(self.x, self.y)
print(abs(Vector(3, 4))) # 5.0
Here "absolute value" means the length of the vector. Keep that meaning intuitive: a magnitude is the natural thing for __abs__() to return. If a class has no __abs__(), calling abs() on it raises a TypeError naming the type.
Common mistakes
- Passing a string.
abs("-5")raisesTypeError: bad operand type for abs(): 'str'. Convert first:abs(int("-5"))orabs(float("-5.5")). - Passing a list or tuple. Apply
abs()to each item, as shown above, or use NumPy. - Expecting
abs()to round. It changes only the sign.abs(-2.7)is2.7. To round the result as well, see how to round numbers in Python. - Confusing absolute value with square root. They are different operations.
abs(-9)is9, while the square root of 9 is 3. For roots, including roots of negative numbers, see square root in Python. - Forgetting the parentheses. Writing
abs -5is a syntax error. The call needs parentheses:abs(-5).
Writing it without abs()
If you ever need to show the logic, a conditional expression does the same for ordinary real numbers:
def absolute(value):
return value if value >= 0 else -value
This returns 7 for -7 and for 7. It does not handle complex numbers, and it is slower and longer than the built-in. It is useful for teaching and for exercises that forbid abs(), and not much else. In real code, write abs(value).
Frequently asked questions
- What is the difference between abs() and math.fabs() in Python?
- abs() is a built-in that accepts integers, floats, complex numbers and any object that implements __abs__(), and it returns a result of the same kind (an int stays an int). math.fabs() is a function in the math module that is meant for real numbers and returns a float. For everyday work, abs() is the one to use.
- How do I get the absolute value of every item in a list in Python?
- Use a list comprehension, [abs(value) for value in numbers], or map(abs, numbers) if you want an iterator. For large numeric arrays, convert them to a NumPy array and call numpy.abs() on the whole array at once.
- What does abs() return for a complex number?
- Its magnitude, which is the distance from the origin on the complex plane. The result is a float, so abs(3+4j) is 5.0.
- Can I write the absolute value without abs()?
- Yes: value if value >= 0 else -value gives the same result for ordinary numbers. It is longer and does not handle complex numbers or custom types, so abs() is the better default.