abs()

Distance from zero: negatives flip positive, positives pass through.

Built-in functionPython 1.0+Live demo
Common call
abs(-5)
Returns
same type as input (complex → float magnitude)
Replaces
delegates to __abs__ — works on Decimal, Fraction, numpy too
Watch out
strings and lists have no abs — TypeError
abs(xxThe number. Any type implementing __abs__ works.type: int | float | complex · required)
int | float

Demo

Live evaluation
Try:
Inputs
xfloatthe number
Output
-5.abs()
5

Sign removed, value kept — ints stay int, floats stay float.

Parameters

NameTypeRequiredDescription
xint | float | complexyesThe number. Any type implementing __abs__ works.

Return value

int | floatThe absolute value, same type as the input. For complex numbers, the magnitude (a float).

Common patterns

Distance between numbers
Order-independent difference.
delta = abs(a - b)
Tolerance comparison
The float-equality workaround — or use math.isclose.
if abs(x - y) < 1e-9:
    treat_as_equal()
Magnitude sorting
abs as a key function.
sorted(deltas, key=abs)

Examples

1. Negative int
abs(-5)
Returns
5
2. Positive float
abs(3.2)
Returns
3.2
3. Zero
abs(0)
Returns
0
4. Complex magnitude
abs(3 + 4j)
Returns
5.0

Pitfalls

1. Non-numbers raise
abs is numeric only — convert strings first.
Raises
abs("-5")
TypeError: bad operand type for abs(): 'str'
Fix
abs(int("-5"))
5
2. The int minimum edge case exists elsewhere, not in Python
Languages with fixed-width ints overflow on abs(INT_MIN); Python ints are arbitrary precision — abs never overflows.
C/Java worry
abs(-2**63)
9223372036854775808 — fine in Python
Nothing to fix
# Python ints grow as needed
no overflow

When to use

Use it
  • Distances and differences
  • Tolerance checks (or math.isclose)
  • Magnitude-based keys for sorted/max/min
Reach for something else
  • Element-wise on arrays → numpy.abs
  • Float equality directly → math.isclose

Notes

Complexity
O(1)
Return
same type as input; complex → float
CPython impl
Python/bltinmodule.c → PyNumber_Absolute → __abs__ slot
Memory
No allocation for small ints (cached)
Thread-safe
Yes — pure computation

FAQ

Yes — implement __abs__ and abs() delegates to it.

class Vector:
    def __abs__(self):
        return math.hypot(self.x, self.y)

History

1.0
One of the original built-ins.