Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I create a python list with a negative index

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.

like image 499
Andrew Avatar asked Dec 11 '14 20:12

Andrew


People also ask

Can Python list have negative index?

Python3. In this, we reverse the list using slicing, and use ~ operator to get negation, index() is used to get the desired negative index.

How do you negative A index in Python?

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.

What is a [- 1 in Python?

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.

How do you create a list in Python illustrate the use of negative index of list with example?

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.


1 Answers

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.

like image 181
elyase Avatar answered Sep 28 '22 10:09

elyase