'How do you make negative values positive using absolutes?
list_1 = [ 10, 20, 40, -19, -4, 30]
desired output = [ 0, 0, 0, 19, 4, 0]
I have a list with a lot of values, some positive and some negative. What is the best methodology to changing the values in the list that are negative into the positive? Next, what is the best methodolgy for changing the positive values to 0?
I feel like it is simple but am getting stuck
Solution 1:[1]
Quite Pythonic and readable to use a list comprehension and if expression here:
>>> input = [10, 20, 40, -19, -4, 30]
>>> [-x if x < 0 else 0 for x in input]
[0, 0, 0, 19, 4, 0]
Solution 2:[2]
Basic list comprehension should do the trick:
[-min(x, 0) for x in list_1]
The rationale is that
- you want to take
min(x, 0)for each elementxin the list. This will change all the positive numbers to 0 while leaving the negative numbers unchanged. - you can then take the negative of the resulting value from step 1 to make the negative numbers positive. Since the positive numbers were already changed to 0, these will stay 0.
For example, if x=5, -min(x, 0) will be 0. If x=-5, -min(x, 0) will be 5.
Solution 3:[3]
A solution without list comprehension.
list_1 = [ 10, 20, 40, -19, -4, 30]
desired_list = []
for i in list_1:
if i < 0:
desired_list.append(-i)
else:
desired_list.append(0)
In this for-loop, we check for every element in list_1, if it is less than 0, then the sign is changed. If not, then a 0 is appended to the desired_list.
Output:
>>> desired_list
[0, 0, 0, 19, 4, 0]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Thomas |
| Solution 2 | |
| Solution 3 |
