Skip to content
Advertisement

How to obtain the absolute value of numbers?

I have a list of numbers that looks like the one below:

JavaScript

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:

JavaScript

Advertisement

Answer

  1. You can use abs and map functions like this

    JavaScript

    Output

    JavaScript
  2. Or you can use list comprehension like this

    JavaScript
  3. Or you can use list comprehension and a simple if else condition like this

    JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement