Let's say you have a negative number and you want to get its absolute value. For this, you can use the
abs() function. The abs() function returns the absolute value of any number (positive, negative, and complex). Below is shown how to get a list of absolute values from a list that contains both negative and positive numbers. We use list comprehension.list1 = [-12, -45, -67, -89, 34, 67, -13]
print([abs(num) for num in list1])
[12, 45, 67, 89, 34, 67, 13]Also,
abs() can be applied to a floating-point number, and it will return the absolute value. See below:num = -23.12
print(abs(num))
23.12➡️ Using the math module
If you need more advanced mathematical functions, you can use
fabs() from the math module. This function always returns a float.import math
num = -23.12
absolute_value = math.fabs(num)
absolute_value
23.12➡️ Using a lambda function
You can also use
lambda to turn a negative number into its absolute value. The code below checks if x is less than zero (that is, if it's a negative value). If so, it returns -x, essentially removing the minus and making the number positive. If x is not negative (greater than or equal to 0), it returns x as it is.num = -23.12
absolute_value = (lambda x: -x if x < 0 else x)(num)
absolute_value
23.12