I have a list of numbers that looks like the one below:
JavaScript
x
2
1
[2, 3, -3, -2]
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:
JavaScript
1
2
1
[2, 3, 3, 2]
2
Advertisement
Answer
You can use
abs
andmap
functions like thisJavaScript131myList = [2,3,-3,-2]
2print map(abs, myList)
3
Output
JavaScript121[2, 3, 3, 2]
2
Or you can use list comprehension like this
JavaScript121[abs(number) for number in myList]
2
Or you can use list comprehension and a simple if else condition like this
JavaScript121[-number if number < 0 else number for number in myList]
2