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
You can use
abs
andmap
functions like thismyList = [2,3,-3,-2] print map(abs, myList)
Output
[2, 3, 3, 2]
Or you can use list comprehension like this
[abs(number) for number in myList]
Or you can use list comprehension and a simple if else condition like this
[-number if number < 0 else number for number in myList]