Home > Software design >  How do you make negative values positive using absolutes?
How do you make negative values positive using absolutes?

Time:03-03

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

CodePudding user response:

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]

CodePudding user response:

Basic list comprehension should do the trick:

[-min(x, 0) for x in list_1]

The rationale is that

  1. you want to take min(x, 0) for each element x in the list. This will change all the positive numbers to 0 while leaving the negative numbers unchanged.
  2. 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.

CodePudding user response:

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]
  • Related