Skip to content
Advertisement

How to obtain the absolute value of numbers?

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]

Advertisement

Answer

  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]
    
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement