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.
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.
Negative Indexes in Lists
Python, negative values aren't out of range in list - Stack Overflow
how do I create a python list with a negative index - Stack Overflow
List slicing with negative index
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.
Using negative numbers starts at the back of the list and counts down, that's why they still work.
When you index into a list, the negative values mean N values from the end. So, -1 is the last item, -5 is the 5th from the end, etc. It's actually quite useful once you are used to it.
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