sam
sam

Reputation: 19164

negation of list in python

I have a list :

v=[0, -0.01, 0, 0, 0.01, 0.25, 1]

I wanted the list to be :

v=[0, 0.01, 0, 0, -0.01, -0.25, -1]

which is the best way to do that? -v wont work.

Upvotes: 2

Views: 489

Answers (1)

falsetru
falsetru

Reputation: 369054

Using list comprehension:

>>> v=[0, -0.01, 0, 0, 0.01, 0.25, 1]
>>> [-x for x in v]
[0, 0.01, 0, 0, -0.01, -0.25, -1]

Using map with operator.neg:

>>> import operator
>>> map(operator.neg, v)
[0, 0.01, 0, 0, -0.01, -0.25, -1]
  • Replace map(..) with list(map(..)) if you use Python 3.x

Using numpy:

>>> import numpy as np
>>> -np.array(v)
array([-0.  ,  0.01, -0.  , -0.  , -0.01, -0.25, -1.  ])
>>> (-np.array(v)).tolist()
[-0.0, 0.01, -0.0, -0.0, -0.01, -0.25, -1.0]

Upvotes: 18

Related Questions