I have a list of numbers that looks like the one below:
[2, 3, -3, -2]
How can I obtain a list of values that contain the absolute value of every value in the above list? In this case it would be:
[2, 3, 3, 2]
The absolute value of a number is the number's distance from zero, which will always be a positive value. To find the absolute value of a number, drop the negative sign if there is one to make the number positive. For example, negative 4 would become 4.
Step-by-step explanation: The absolute value of a number is its distance from zero on the number line. For example, -7 is 7 units away from zero, so its absolute value would be 7. And 7 is also 7 units away from zero, so its absolute value would also be 7.
For example,|2| represents the absolute value of 2. To calculate it, it is important to have some familiarity with the representation of integers on a number line. So if you would like to review a bit before we continue, I would recommend this previous post explaining how to place numbers on a number line.
Therefore, the absolute value of -4 is 4.
You can use abs
and map
functions like this
myList = [2,3,-3,-2]
print map(abs, myList)
Output
[2, 3, 3, 2]
Or you can use list comprehension like this
[abs(number) for number in myList]
Or you can use list comprehension and a simple if else condition like this
[-number if number < 0 else number for number in myList]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With