Python abs() Built-in Function (Syntax & Usage)
Python’s built-in abs() returns the nonnegative value of a real number and the magnitude of a complex number. Call it with one argument: abs(number). Integers, floats, and complex values are common inputs, and custom objects can define the same behavior with __abs__(). Learn what it returns, where precision matters, and how to use it safely.
Do you fit coding practice around work, study, or a busy day? If so, a small built-in function that makes your code easier to read can be useful. I teach abs() by starting with familiar numbers, then checking how the result changes for floats and complex values. That simple sequence helps prevent a common mistake: assuming the function always returns a positive integer.
Python abs() overview: purpose, syntax, and supported inputs
abs() is a built-in function that gives a number’s absolute value or magnitude. Its syntax is abs(number), with one required argument and no optional parameters. For real numbers, the result is nonnegative. For complex numbers, the result is their distance from zero in the complex plane.
You do not need to import a module to use abs(). Python makes it available by default.
print(abs(-8)) # 8
print(abs(8)) # 8
print(abs(0)) # 0
For real numbers, absolute value describes distance from zero. Both -8 and 8 are eight units from zero, so both calls return 8. The function does not change the variable you pass in:
value = -8
result = abs(value)
print(value) # -8
print(result) # 8
The variable remains -8; abs() returns a result. This distinction matters when you use it in a calculation or assign the result to a new variable.
| Expression | Result | Result type |
|---|---|---|
abs(-8) |
8 |
int |
abs(-3.5) |
3.5 |
float |
abs(3 + 4j) |
5.0 |
float |
abs(0) |
0 |
int |
The examples show common behavior, not a rule that every result has the same type. The input type and its definition of absolute value affect the return value.
Return values, numeric types, and edge cases
The return value depends on the input. For built-in integers and floats, abs() returns a nonnegative value of the same numeric type. For a complex number, it returns a float representing magnitude. Some other numeric types and custom objects also support the operation.
Integers and floating-point numbers
For an integer, abs() returns its nonnegative magnitude as an integer. For a float, it returns a nonnegative float. The function also works for positive values and zero, so you do not need a separate check for the sign.
abs(-12) # 12
abs(12) # 12
abs(-2.75) # 2.75
abs(0.0) # 0.0
A float can also represent special values. For example, abs(float("inf")) is infinity, and abs(float("nan")) is still NaN, a value used to represent an undefined or unavailable numeric result. These values do not behave like ordinary finite numbers, so handle them according to your program’s needs.
Complex numbers
A complex number has a real part and an imaginary part. Python writes the imaginary part with j, as in 3 + 4j. For a complex input, abs() returns its magnitude, calculated in mathematical terms as the square root of the real part squared plus the imaginary part squared.
value = 3 + 4j
print(abs(value)) # 5.0
The magnitude is 5.0, not 5 + 0j. This is why treating abs() as a function that “makes a number positive” is incomplete: complex numbers are not ordered as positive or negative in the same way as real numbers.
Other numeric types and custom objects
abs() is not limited to the three most familiar built-in numeric types. Other numeric types may support it too. A class can define the operation by implementing the special method __abs__(). That method tells Python what abs(instance) should mean for that class.
class Measurement:
def __init__(self, value):
self.value = value
def __abs__(self):
return abs(self.value)
reading = Measurement(-2.5)
print(abs(reading)) # 2.5
Here, the class chooses to base its result on the stored value. When you write a custom __abs__(), make its behavior clear and return a value that fits the meaning of the type.
If an object does not support the operation, Python raises TypeError:
abs("hello") # TypeError
Check that a value is numeric before calling abs() when its type is uncertain. In a small script, a direct call may be enough; in a larger program, validate inputs at the point where they enter your code.
Examples, testing strategies, and common misconceptions
Testing abs() means checking more than a negative integer. Try positive, negative, and zero values, then test floats, complex numbers, and any custom type your program uses. This small set of cases confirms both the returned value and the type your later code can expect.
A practical test set might look like this:
values = [-8, 8, 0, -3.5, 3 + 4j]
for value in values:
result = abs(value)
print(value, result, type(result).__name__)
Expected results include 8 for -8, 3.5 for -3.5, and 5.0 for 3 + 4j. Testing zero is useful because it confirms that the function handles the boundary between negative and positive values.
A few misconceptions are worth avoiding:
- “
abs()always returns an integer.” It does not. A float input returns a float, and a complex input returns a float. - “It only accepts negative numbers.” Positive values and zero are valid inputs too.
- “It works on every object.” Unsupported objects raise
TypeError. - “A tiny float result must be exactly zero.” Floating-point calculations can leave a small remainder because many decimal fractions cannot be represented exactly in binary.
For example:
difference = 0.1 + 0.2 - 0.3
print(abs(difference)) # a very small positive value, not exactly 0.0
The exact displayed value can depend on the calculation and Python version, but the important point is that it may not be zero. Avoid testing computed floats with exact equality when a small rounding difference is acceptable. Instead, compare the difference with a tolerance that fits the task:
actual = 0.1 + 0.2
expected = 0.3
tolerance = 1e-9
if abs(actual - expected) <= tolerance:
print("Close enough")
The tolerance here is an example, not a universal threshold. Choose one based on the scale and accuracy needs of your calculation. For a direct comparison of two floats, Python’s math.isclose() is another option; review its relative and absolute tolerance settings for your use case.
Practical uses in data analysis, error measurement, and code
abs() is useful whenever the size of a difference matters more than its direction. Common examples include measuring distance between values, checking the size of a calculation error, or working with the magnitude of a complex number. State what your inputs represent before deciding how to interpret the result.
Measuring a difference or error
Subtracting two real values gives a signed difference. Applying abs() gives the size of that difference without regard to which value is larger:
target = 100
measured = 97
difference = abs(target - measured)
print(difference) # 3
This can make a tolerance check easy to read:
if abs(measured - target) <= 5:
print("Within the allowed range")
In this example, the allowed difference is five units. In real code, the correct limit depends on the measurement or requirement; abs() does not choose it for you.
Working with complex values
For a complex number, abs() gives a magnitude. This can be useful when a program needs the size of a complex result rather than its real and imaginary parts separately.
signal = 3 + 4j
magnitude = abs(signal)
print(magnitude) # 5.0
Do not confuse that operation with calculating the absolute values of the real and imaginary components separately. For 3 + 4j, the magnitude is 5.0, while the component values are 3 and 4.
Checking a custom type
When you use abs() with an object from your own class, check the class’s __abs__() method. Ask what the result represents, what type it returns, and how it handles zero or unusual inputs. Those details are part of the class’s behavior, not a universal rule imposed by the built-in function.
For arrays, check the library you are using. A Python list, a NumPy array, and a custom numeric object do not necessarily share the same behavior. The built-in function is a clear choice for a single supported value; array libraries often provide their own operations for element-by-element work.
A reliable workflow is simple: identify the input type, call abs(), confirm the expected result type, and test boundary values. For floating-point comparisons, set a justified tolerance rather than expecting exact decimal arithmetic.
Frequently asked questions about abs()
What is the syntax for abs() in Python?
Use abs(number). It takes one required argument and has no optional parameters.
Does abs() change the original value?
No. It returns a result and does not change the value stored in the variable you passed.
What does abs(-8) return?
It returns the integer 8.
What does abs(-3.5) return?
It returns the float 3.5.
What does abs(3 + 4j) return?
It returns the float 5.0, the complex number’s magnitude.
Does abs() always return a positive number?
For real numeric inputs, it returns a nonnegative value. Complex inputs have a magnitude, not a positive or negative sign.
What happens if I pass a string?
A string does not support this operation by default, so abs("hello") raises TypeError.
Can a custom class work with abs()?
Yes. A class can define __abs__() to specify the result of abs(instance).
Why can abs() return a tiny value instead of zero?
A calculation using floats may have a small rounding difference. Compare against an appropriate tolerance when exact equality is not suitable.
Where can I check the official behavior?
See the Python documentation for the built-in abs() function and the data model’s __abs__() method. Use the documentation version that matches your interpreter: docs.python.org/3/library/functions.html#abs and docs.python.org/3/reference/datamodel.html#object.__abs__.
The key point is to match your expectations to the input type: real values produce nonnegative values, complex values produce magnitudes, and unsupported objects raise an error. Test the cases your code actually uses, especially floating-point boundaries and custom types.
(This article was written by one of our staff writers, Andrew Kensington. Visit our Meet the Team page.)
