Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to obtain the absolute value of numbers?

Tags:

python

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]
like image 649
Guangyue He Avatar asked Dec 30 '13 03:12

Guangyue He


People also ask

How do you find the absolute value of a number?

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.

What is the absolute number of 7?

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.

What is the absolute value of 2 is 2?

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.

What's the absolute value of 4?

Therefore, the absolute value of -4 is 4.


1 Answers

  1. You can use abs and map functions like this

    myList = [2,3,-3,-2]
    print map(abs, myList)
    

    Output

    [2, 3, 3, 2]
    
  2. Or you can use list comprehension like this

    [abs(number) for number in myList]
    
  3. Or you can use list comprehension and a simple if else condition like this

    [-number if number < 0 else number for number in myList]
    
like image 66
thefourtheye Avatar answered Oct 31 '22 08:10

thefourtheye