I am trying to turn a list of positive numbers into a list of negative numbers with the same value in python 3.3.3
For example turning [1,2,3]
into
There is also this method:
Little note, this will only work if all numbers start positive. It won't affect 0. If you have negative numbers you don't want changing you need to add the IF statement below.
if num < 0: continue
numbers = [1, 2, 3, 4 ,5]
for num in numbers:
numbers[num-1] = num - (2*num)
numbers
[-1, -2, -3, -4, -5]
You can use the numpy package and do numpy.negative()
The most natural way is to use a list comprehension:
mylist = [ 1, 2, 3, -7]
myneglist = [ -x for x in mylist]
print(myneglist)
Gives
[-1, -2, -3, 7]
If you want to modify a list in place:
mylist = [ 1, 2, 3, -7]
print(mylist)
for i in range(len(mylist)):
mylist[i] = -mylist[i]
print(mylist)
For large list, you will probably better use numpy
import numpy as np
a=np.array([1,2,3,4])
# result as a numpy array
b=-a
# can be casted back to list
c=list(b)