# Negative array indicies and slice()

Andrew andrewr3mail at gmail.com
Mon Oct 29 05:09:56 CET 2012

```On Sunday, October 28, 2012 8:43:30 PM UTC-7, Ian wrote:
> On Sun, Oct 28, 2012 at 9:12 PM,  <Andrew> wrote:
>
> > The slice operator does not give any way (I can find!) to take slices from negative to positive indexes, although the range is not empty, nor the expected indexes out of range that I am supplying.
>
> >
>
> > Many programs that I write would require introducing variables and logical statements to correct the problem which is very lengthy and error prone unless there is a simple work around.
>
> >
>
> > I *hate* replicating code every time I need to do this!
>
> >
>
> > I also don't understand why slice() is not equivalent to an iterator, but can replace an integer in __getitem__() whereas xrange() can't.
>
> >
>
> >
>
> > Here's an example for Linux shell, otherwise remove /bin/env...
>
> > {{{#!/bin/env python
>
> > a=[1,2,3,4,5,6,7,8,9,10]
>
> > print a[-4:3]  # I am interested in getting [7,8,9,10,1,2] but I get [].
>
> > }}}
>
>
>
>
>
> For a sequence of length 10, "a[-4:3]" is equivalent to "a[6:3]",
>
> which is an empty slice since index 6 is after index 3.
>
>
>
> If you want it to wrap around, then take two slices and concatenate
>
> them with "a[-4:] + a[:3]".

Hi Ian,
Well, no it really isn't equivalent; although Python implements it as equivalent.

Consider a programmer who writes:
xrange(-4,3)

They clearly *want* [-4,-3,-2,-1,0,1,2]

That is the "idea" of a range; So, for what reason would anyone want -4 to +3 to be 6:3???  Can you show me some code where this is desirable??

I do agree that the data held in -4 is equivalent to the data in 6, but the index is not the same.

So: Why does python choose to convert them to positive indexes, and have slice operate differently than xrange -- for the slice() object can't possibly know the size of the array when it is passed in to __getitem__;  They are totally separate classes.

I realize I can concat. two slice ranges, BUT, the ranges do not always span from negative to positive.

eg: a line in my program reads:
a[x-5:x]

if x is 7, then this is a positive index to a positive index.
So, there is no logic to using two slices concatd !

I use this arbitrary range code *often* so I need a general purpose solution.
I looked up slice() but the help is of no use, I don't even know how I might overload it to embed some logic to concatenate ranges of data; nor even if it is possible.
```