How to obtain the absolute value of numbers?

Guangyue He picture Guangyue He · Dec 30, 2013 · Viewed 49.3k times · Source

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]

Answer

thefourtheye picture thefourtheye · Dec 30, 2013
  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]