A Denver coffee shop owner asked me why her six-month report said she’d missed budget by only $2,214.10. The overruns and savings were cancelling out. Taking the Python absolute value of each month with abs() before summing showed the real miss: $4,798.60.
Summing the raw variances is the obvious move, and it’s wrong for this question, because a $980.00 overspend erases a $980.00 saving.
Quick answer: call the built-in abs() on any number:
abs(-1250.75) # 1250.75
abs(-42) # 42
abs(3 + 4j) # 5.0
In this tutorial, I’ll show you how I get a Python absolute value with abs() and math.fabs(), for whole lists, NumPy arrays and pandas columns, your own classes, and without abs() at all. My runs used Python 3.12.5.
How does abs() return the absolute value in Python?
Every example reads the same six months from budget.py: negative means under budget, positive means over.
# 2026 monthly spend vs. budget for a Denver coffee shop (USD)
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun"]
variances = [-1250.75, 980.00, -45.50, 0.0, 312.25, -2210.10]
abs() works on int, float, Decimal, Fraction and even complex numbers, where it returns the distance from zero:
from decimal import Decimal
from fractions import Fraction
from budget import variances
print(abs(-1250.75), abs(-42), abs(17))
print(abs(Decimal("-19.99")), abs(Fraction(-3, 4)))
print(abs(3 + 4j))
print(f"Net variance: ${sum(variances):,.2f}")
total = sum(abs(v) for v in variances)
print(f"Total missed: ${total:,.2f}")
Output:
1250.75 42 17
19.99 3/4
5.0
Net variance: $-2,214.10
Total missed: $4,798.60

An int stays an int and a Decimal stays a Decimal, which matters for money. abs(3 + 4j) is 5.0, the length of the 3-4-5 triangle.
Get the absolute value of every number in a list
Same six months, now as a clean list of misses. A list comprehension or map(abs, ...) does it in one line:
from budget import months, variances
misses = [abs(v) for v in variances]
print(misses)
print(list(map(abs, variances)) == misses)
worst = max(variances, key=abs)
i = variances.index(worst)
print(f"Biggest miss: {months[i]} ({worst:+,.2f})")
print(sorted(variances, key=abs))
Output:
[1250.75, 980.0, 45.5, 0.0, 312.25, 2210.1]
True
Biggest miss: Jun (-2,210.10)
[0.0, -45.5, 312.25, 980.0, -1250.75, -2210.1]

Passing key=abs to the max() function or sorted() compares by size but returns the original value, so June comes back as -2,210.10, not 2,210.10.
The same pattern answers “how far apart are two numbers?”: abs(a - b). See how to subtract two numbers in Python for the basics.
math.fabs() vs abs(): which one should you use?
math.fabs() always returns a float and only takes real numbers. Here’s what that changes:
import math
print(abs(-42), math.fabs(-42))
print(type(abs(-42)).__name__, type(math.fabs(-42)).__name__)
big = -(2**60 + 1)
print(abs(big))
print(math.fabs(big))
try:
math.fabs(3 + 4j)
except TypeError as err:
print("TypeError:", err)
Output:
42 42.0
int float
1152921504606846977
1.152921504606847e+18
TypeError: must be real number, not complex

A float holds about 15-17 significant digits, so math.fabs() rounds large integers. That’s a floating-point limit, not a bug.
abs() | math.fabs() | |
|---|---|---|
| Import needed | No | import math |
| Return type | Same as input | Always float |
| Complex numbers | Magnitude | TypeError |
| Big integers | Exact | Rounded |
I use abs() almost everywhere; you only need math.fabs() when the next step expects a float.
How to get the absolute value in Python without using abs()
You’ll get this one in interviews and coding exercises. Here are four ways you can write it, run on the same variances:
from budget import variances
def abs_if(x):
if x < 0:
return -x
return x
def abs_ternary(x):
return -x if x < 0 else x
def abs_max(x):
return max(x, -x)
def abs_sqrt(x):
return (x * x) ** 0.5
for v in variances:
row = [f(v) for f in (abs_if, abs_ternary, abs_max, abs_sqrt)]
print(f"{v:>9} -> {row}")
print("sqrt trick on 1e200:", abs_sqrt(-1e200))
Output:
-1250.75 -> [1250.75, 1250.75, 1250.75, 1250.75]
980.0 -> [980.0, 980.0, 980.0, 980.0]
-45.5 -> [45.5, 45.5, 45.5, 45.5]
0.0 -> [0.0, 0.0, 0.0, 0.0]
312.25 -> [312.25, 312.25, 312.25, 312.25]
-2210.1 -> [2210.1, 2210.1, 2210.1, 2210.1]
sqrt trick on 1e200: inf

if/else and the ternary are the same idea: flip the sign with -x (or x * -1) when the number is negative. max(x, -x) picks the positive of the pair.
The square root of the square works for small floats, but x * x overflows to inf above about 1e154. More on that in square root in Python.
For integers there’s also a bitwise trick borrowed from C:
def abs_bits(n):
"""Integers only: two's-complement trick."""
mask = n >> 63
return (n ^ mask) - mask
for n in (-42, 17, -2**63, -(2**70 + 5)):
print(n, abs_bits(n), abs_bits(n) == abs(n))
Output:
-42 42 True
17 17 True
-9223372036854775808 9223372036854775808 True
-1180591620717411303429 1180591620717411303685 False
n >> 63 gives -1 for a negative int and 0 otherwise; XOR and subtract then flip the sign. It breaks once an integer goes past 64 bits, which is why it only belongs in C-style puzzles. I’d still write abs() in real code.
Absolute values in NumPy arrays and pandas columns
If you have thousands of rows, skip the Python loop. np.abs() and Series.abs() work on the whole column at once (NumPy 2.5.3, pandas 3.0.6):
import numpy as np
import pandas as pd
from budget import months, variances
arr = np.array(variances)
print(np.abs(arr))
col = pd.Series(variances, index=months, name="miss")
print(col.abs().sort_values(ascending=False).head(3))
Output:
[1250.75 980. 45.5 0. 312.25 2210.1 ]
Jun 2210.10
Jan 1250.75
Feb 980.00
Name: miss, dtype: float64
pandas lists June, January and February as the three biggest misses. For np.absolute(), complex arrays and 2-D data, see the NumPy absolute value tutorial.
Make abs() work on your own class with __abs__()
abs(obj) calls obj.__abs__(), so you can define what “size” means for any class. Here it’s the straight-line distance of a delivery offset:
import math
class Offset:
"""Delivery drop-off offset in miles (east, north)."""
def __init__(self, east, north):
self.east, self.north = east, north
def __abs__(self):
return math.hypot(self.east, self.north)
print(abs(Offset(-3, 4)))
print(f"{abs(Offset(1.2, -0.5)):.2f} miles")
Output:
5.0
1.30 miles
math.hypot() returns the distance from the two legs, so (-3, 4) is 5.0 miles. Return a number from __abs__() so the result is easy to sum.
Common errors with absolute value in Python
typed = "-19.99" # input() always returns text
try:
abs(typed)
except TypeError as err:
print("TypeError:", err)
print(abs(float(typed)))
try:
abs(None)
except TypeError as err:
print("TypeError:", err)
print(abs(-0.0), -0.0 < 0)
Output:
TypeError: bad operand type for abs(): 'str'
19.99
TypeError: bad operand type for abs(): 'NoneType'
0.0 False
TypeError: bad operand type for abs(): ‘str’. input() returns text, so convert the string to a float first.
‘NoneType’ in the same error. A missing value slipped in. Filter out None before you call abs().
Negative zero. -0.0 < 0 is False, so an if/else version returns -0.0 unchanged, while abs(-0.0) gives 0.0.
Doing more number crunching? I’d read these next:
- Round numbers in Python
- Print 2 decimal places in Python
- Get the decimal part of a number in Python
- Convert a float to an int in Python
Frequently asked questions
How do you get the absolute value in Python?
Call the built-in abs(x). It returns the number without its sign: abs(-7.5) is 7.5.
Is there a math.abs() in Python?
No. The math module has math.fabs(), which always returns a float. The built-in abs() needs no import.
How do I get the absolute value without abs()?
Use -x if x < 0 else x or max(x, -x). Both match abs() for ordinary numbers.
How do I take the absolute value of a list?
Use [abs(x) for x in nums] or list(map(abs, nums)). For NumPy arrays use np.abs(arr).
What does abs() return for a complex number?
Its magnitude as a float. abs(3 + 4j) returns 5.0.
Where is abs() documented?
See abs() in the Python docs.

Bijay Kumar is a 13-time Microsoft MVP with more than 18 years in software development, and the founder of Python Guides and TSinfo Technologies. He started out building .NET and SharePoint solutions at HP, TCS and KPIT before moving into Python, machine learning and AI, and he also builds web apps with TypeScript and React. He writes the tutorials here himself, and every example is run before publishing so you see the real output. More about Bijay