Python abs() Function

The abs() built-in Python function calculates absolute value of a number.

It takes one input x.

  • For negative numbers (x < 0) it returns -x.
  • For positive numbers and zero (x >= 0) it returns x.

Input data types

Typical arguments to the abs() function are int or float types.

>>> abs(3)
3
>>> abs(-3)
3
>>> abs(0)
0
>>> abs(3.5)
3.5
>>> abs(-3.5)
3.5

The argument to abs() can be object of any class which implements the __abs__() method, such as Decimal or Fraction:

>>> from decimal import Decimal
>>> x = Decimal('-7.25')
>>> x
Decimal('-7.25')
>>> abs(x)
Decimal('7.25')

>>> from fractions import Fraction
>>> y = Fraction(-1, 3)
>>> y
Fraction(-1, 3)
>>> abs(y)
Fraction(1, 3)

The argument can't be a str, tuple, list, set, or dict. These raise TypeError.

>>> abs('-3.5')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: bad operand type for abs(): 'str'

>>> abs((1, -1))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: bad operand type for abs(): 'tuple'

Official documentation

https://docs.python.org/3/library/functions.html#abs

By remaining on this website or using its content, you confirm that you have read and agree with the Terms of Use Agreement.

We are not liable for any damages resulting from using this website. Any information may be inaccurate or incomplete. See full Limitation of Liability.

Content may include affiliate links, which means we may earn commission if you buy on the linked website. See full Affiliate and Referral Disclosure.

We use cookies and similar technology to improve user experience and analyze traffic. See full Cookie Policy.

See also Privacy Policy on how we collect and handle user data.

© 2024 PyTut