user2837162
user2837162

Reputation:

Invert negative values in a list

I am trying to convert a list that contains negative values, to a list of non-negative values; inverting the negative ones. I have tried abs but it didn't work.

My input is

x = [10,9,8,7,6,5,4,3,2,1,0,-1,-2,-3,-4,-5,-6,-7,-8,-9,-10]

How can I make it into this format as I am trying calculate the area

x = [10,9,8,7,6,5,4,3,2,1,0,1,2,3,4,5,6,7,8,9,10]

Upvotes: 4

Views: 8818

Answers (5)

tommy.carstensen
tommy.carstensen

Reputation: 9622

This is a wrong answer to your question, but this is what I came here looking for. This is how to invert all the numbers in your list using operator.neg; i.e. also positives to negatives.

import operator
x = [10,9,8,7,6,5,4,3,2,1,0,-1,-2,-3,-4,-5,-6,-7,-8,-9,-10]
x = list(map(operator.neg, x))

It returns:

[-10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Or you can do a list comprehension of course:

x = [-xi for xi in x]

Upvotes: 1

aIKid
aIKid

Reputation: 28242

Your attempt didn't work because abs() takes an integer, not a list. To do this, you'll have to either loop through the list:

x = [10,9,8,7,6,5,4,3,2,1,0,-1,-2,-3,-4,-5,-6,-7,-8,-9,-10]
for i in range(len(x)):
     x[i] = abs(x[i])

Or you can use list comprehension, which is shorter:

x = [abs(i) for i in x]

Or simply use the built-in map function, which is even shorter :)

x = list(map(abs, x))

Hope this helps!

Upvotes: 5

Jamil Seaidoun
Jamil Seaidoun

Reputation: 969

what you want is to use the absolute value (|x| = x if x > 0, |x| = -x if x < 0)

for index in range(len(x)):
    x[index] =  x[index] if x[index] > 0 else -x[index]

Upvotes: 1

Brian Hayden
Brian Hayden

Reputation: 370

The simple pythonic way is the list comprehension above but if you're using Numpy for anything else you could do:

x2 = numpy.abs(x)

with no need to convert or do any looping.

Upvotes: 4

Christian Ternus
Christian Ternus

Reputation: 8492

Try a list comprehension:

x2 = [abs(k) for k in x]

Upvotes: 9

Related Questions