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]
Answer from Anton on Stack OverflowNegative Indexes in Lists
python - Negative list index? - Stack Overflow
Generate list of numbers and their negative counterparts in Python - Stack Overflow
how do I create a python list with a negative index - Stack Overflow
I see how useful using the -1 index can be for lists but is there any world where youโd actually need to use a -3 index (in a list of 4) etc. instead of the zero index? Iโm new to coding so I want to learn as much as possible but Iโm not sure of any case (as of right now) where this would be necessary.
Negative numbers mean that you count from the right instead of the left. So, list[-1] refers to the last element, list[-2] is the second-last, and so on.
List indexes of -x mean the xth item from the end of the list, so n[-1] means the last item in the list n. Any good Python tutorial should have told you this.
It's an unusual convention that only a few other languages besides Python have adopted, but it is extraordinarily useful; in any other language you'll spend a lot of time writing n[n.length-1] to access the last item of a list.
I am unsure if order matters, but you could create a tuple and unpack it in a list comprehension.
nums = [y for x in range(6,10) for y in (x,-x)]
print(nums)
[6, -6, 7, -7, 8, -8, 9, -9]
Create a nice and readable function:
def range_with_negatives(start, end):
for x in range(start, end):
yield x
yield -x
Usage:
list(range_with_negatives(6, 10))
That is how you get a convenient one-liner for anything. Avoid trying to look like a magic pro hacker.
If you are using Quantopian, it is advisable that you become familiar with numpy and pandas. For example:
>>> import numpy as np
>>> -1*np.arange(20)
array([ 0, -1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12,
-13, -14, -15, -16, -17, -18, -19])
Then you will have a[1]==-1, a[5]==-5, etc.
the only thing that strikes me is
for i in xrange( -20, 0, -1 ):
seems very wrong since the third argument is step size... you will go -1 per step starting at -20, means next number is -21
and the following is a syntax error
a = []
a[0] = 5
you should do a = [None]*20