w3resource

Python: abs() function

abs() function

The abs() function is used to get the absolute (positive) value of a given number.

The argument may be an integer or a floating point number. If the argument is a complex number, its magnitude is returned.

Syntax:

abs(x)
Python: Built-in function - abs function()

Version:

(Python 3)

Parameter:

Name Description Required / Optional
number Numeric value. Required

If x is a complex number function returns it's magnitude. The absolute value  of a complex number z = x + yj is

\textstyle r=|z|=\sqrt{x^2+y^2}.\,

Return value:

Return the absolute value of a number.

Pictorial Presentation:

Python: Built-in-function - abs() function

Example: Python abs() function

print(abs(-100))
print(abs(1023))
print(abs(123.25))
print(abs(-2033.66))

Output:

100             
1023           
123.25      
2033.66

In Python abs() works with integers and complex numbers. It's return type depends on the type of its argument.

>>> type(-2)
<class 'int'>
>>> type(abs(-2))
<class 'int'>
>>> type(-2.0)
<class 'float'>
>>> type(3+4j)
<class 'complex'>
>>> type(abs(3+4j))
<class 'float'>
>>> 

Get absolute value of numbers of a list:

nums = [12,30,-33,-22,77,-100]
print("Original list:")
print(nums)
print("\nAbsolute values of the above numbers:")
print([abs(x) for x in nums])

Output:

Original list:
[12, 30, -33, -22, 77, -100]

Absolute values of the above numbers:
[12, 30, 33, 22, 77, 100]

Convert a negative number to positive number:

n = -452
print(n)
print(abs(n))
n = -123.45
print(n)
print(abs(n))

Output:

-452
452
-123.45
123.45

Python Code Editor:

Previous: Python Built-in Functions
Next: all()

Test your Python skills with w3resource's quiz



Follow us on Facebook and Twitter for latest update.