2

Is there any way in Python to give the opposite of each numeral element of a list in one line, without doing, for example:

list_ = list(range(10))
for x in range(len(list_)):
    list_[x] = -list_[x]

In this case, considering the list

[0, 1, 2, 3..., 9]

the output should be

[0, -1, -2, -3..., -9]

Every number of the list should be its opposite.


I tried -list_ but it didn't work.

I searched but I found only how to reverse a list, and not how to oppose its elements (I hope this is the correct word, meaning that each number should end up being its additive inverse.)


I know about list comprehensions, but I was wondering if there was a special keyword in Python to achieve this.

D_00
  • 1,440
  • 2
  • 13
  • 32

4 Answers4

3

One way would be to use numpy arrays which have the properties you want:

import numpy as np

list_ = np.array(range(10))
list_inv = - list_

Which gives

[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
D_00
  • 1,440
  • 2
  • 13
  • 32
user_na
  • 2,154
  • 1
  • 16
  • 36
2
list_ = range(10)
list_ = [-x for x in list_]

or

list_ = range(10)
list_ = list(map(lambda x: -x, list_))

or

list_ = range(0,-10,-1)
Vulwsztyn
  • 2,140
  • 1
  • 12
  • 20
2

If your input values are numeric, you can do something like this

negated_values=map(lambda x:-x, mylist)

where

print(list(negated_values))

returns

[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
Kleber Noel
  • 303
  • 3
  • 9
2

If you want to invert a list without using either a list comprehension or map as others have suggested (i.e. the simplest possible single command) you could do it with Numpy, but you'd have to convert to a Numpy array first (which obviously adds its own complexity). Then you can just negate the array e.g.

import numpy as np

x = [1, -2, 3]
arr = np.array(x)

arr    
Output: array([ 1, -2,  3])

-arr
Output: array([-1,  2, -3])
David Buck
  • 3,752
  • 35
  • 31
  • 35