I'm new to python and need to create a list with a negative index but have not been successful so far.
I'm using this code:
a = []
for i in xrange( -20, 0, -1 ):
    a[i] = -(i)
    log.info('a[{i}]={v}'.format(i=i, v=a[i]))
else:
    log.info('end')
and getting the log output as
end
Incidentally I'm using a site call quantopian so the log.info is from their infrastructure and just print out the output into a web console.
What am I doing wrong?
Thanks in advance for your help.
Python3. In this, we reverse the list using slicing, and use ~ operator to get negation, index() is used to get the desired negative index.
Negative Index As an alternative, Python supports using negative numbers to index into a string: -1 means the last char, -2 is the next to last, and so on. In other words -1 is the same as the index len(s)-1, -2 is the same as len(s)-2.
Python also allows you to index from the end of the list using a negative number, where [-1] returns the last element. This is super-useful since it means you don't have to programmatically find out the length of the iterable in order to work with elements at the end of it.
You can't create a list with negative indices. They start with zero and count up by 1. If you use a negative index when accessing an element, Python converts that to a positive index relative to the end of the list.
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. 
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With