Python 3 reference · Built-in Functions

Python abs() Function

Return the absolute value of a number: its distance from zero, so negative numbers become positive.

Python 3 Since 3.0

Syntax

abs(x)

Parameters

ParameterDescription
x An int, float or complex number (or any object with an __abs__() method).

Return value

The absolute value, of the same numeric type. For a complex number, its magnitude as a float.

Examples

Integers and floatsTry it yourself
print(abs(-7))
print(abs(3.5))
print(abs(-0.25))

Output

7
3.5
0.25
Distance between two valuesTry it yourself
# The distance between two temperatures, whichever is larger
today, yesterday = 18, 23
print(abs(today - yesterday))

Output

5
Complex numbersTry it yourself
print(abs(3 + 4j))  # the length of the vector (3, 4)

Output

5.0

Good to know

  • abs() never changes the type of an int or float: abs(-2) is 2, abs(-2.0) is 2.0.
  • For a complex number it returns the magnitude sqrt(real² + imag²), always a float.
  • Your own classes can support abs() by defining __abs__().

Version history

VersionChange
Python 3.0Added