89DEVs

Python abs() function - absolute value

How do you absolute a number in Python?

To find the absolute value of a given number, use the Python function abs(). It is a built-in function, so no import is necessary to use it. abs() returns the absolute value for a given integer or float. If the given argument is a complex number, the magnitude of it is returned.

absolute value of integer

If an integer is given, the abs() function returns the absolute value of the integer. print(abs(-10)) 10

absolute value of float

If a float value is given, the abs() function returns the absolute value of the float. print(abs(-5.555)) 5.555

absolute value of complex number

If a complex number is given, the abs() function returns the magnitude of the complex number. print(abs(3 - 4j)) 5.0

absolute value of list elements

To apply the abs() function to a list we can use list comprehension or the map() function. # absolute value of list using list comprehension myList = [-5, -2, 5, 3, -5.555, - 4j] NewList = [abs(element) for element in myList] print(NewList) The NewList only containing non-negative numbers is returned. [5, 2, 5, 3, 5.555, 4.0] Alternatively, we can achieve the same result by using the map() function. # absolute value of list using map() function myList = [-5, -2, 5, 3, -5.555, - 4j] NewList = list(map(abs, myList)) print(NewList) The same NewList is returned. [5, 2, 5, 3, 5.555, 4.0]

abs() syntax

The syntax of the abs() function is: abs(number)

abs() arguments

The abs() function takes a single argument. If more or less than one argument is given, a TypeError occurs. The argument can be of type integer, float or complex number. If any other type like string is given, a TypeError occurs.

abs() return value

The abs() function returns for integers the absolute integer value, for float types the absolute float value and for complex numbers the magnitude.

                
        

Summary


Click to jump to section