Negative array indicies and slice()

Ian Kelly ian.g.kelly at gmail.com
Mon Oct 29 00:25:28 EDT 2012


On Sun, Oct 28, 2012 at 10:00 PM,  <andrewr3mail at gmail.com> wrote:
> Hi Ian,
> Well, no it really isn't equivalent.
> Consider a programmer who writes:
> xrange(-4,3) *wants* [-4,-3,-2,-1,0,1,2]
>
> That is the "idea" of a range; for what reason would anyone *EVER* want -4 to +3 to be 6:3???

That is what ranges do, but your question was about slices, not ranges.

> 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.

Ranges can contain negative integers.  However, sequences do not have
negative indices.  Therefore, negative indices in slices are used to
count from the end instead of from the start.  As stated in the
language docs, "If either bound is negative, the sequence’s length is
added to it."  Therefore, "a[-4:3]" does not wrap around the end of
the sequence because "a[6:3]" does not wrap around the end of the
sequence.

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

def wrapping_slice(seq, start, stop):
    start, stop, _ = slice(start, stop).indices(len(seq))
    if start <= stop:
        return seq[start:stop]
    else:
        return seq[start:] + seq[:stop]

You'll have to decide for yourself whether you want it to return an
empty list or the entire list if start == stop.



More information about the Python-list mailing list