Slice objects with negative increment

Alex Martelli aleax at aleax.it
Tue Apr 30 16:23:59 EDT 2002


Paul Hughett wrote:
        ...
> Hmm.  Is the value of r[-1:-1:-1] equal to array([12, 11, 10, 9, 8, 7,
> 6, 5, 4, 3, 2, 1, 0]) or to an empty array?  It could plausibly be

Any slice x[a:a] is empty.  Why ever should x[a:a:-1] be any different
from x[a:a:1]?!  I suggest you download and install Numeric so you
can easily check on such doubts.

Slicing rules are simple.  All indices, positives or negatives, indicate
specific items.  Too-small indices point "before the start"; too-large 
ones, "after the end", as does a missing stop -- there's no IndexError as 
there could be in indexing.  If start is missing it's the first if stride>0,
the last if stride<0; if stop it's missing it's after-the-end if stride>0,
before-the-start if stride<0.

OK, so look at the start and stop items after this normalization.  The
slice is empty if they're the same, if start is after stop and stride>0,
if start is before stop and stride<0.

If the slice is not empty, the start element is included.  Now add
(algebraically, i.e. including sign) the stride to the index of the start
element to get "another start element" and go back to the previous
paragraph to see if the overall result slice is finished or if you need
to keep repeating this.

Apart from the normalization of negative and out-of-range indices,
these are the same rules that range and xrange use, except they
return "the indices", so to speak, rather than any items.


> In any case, I will be adopting the Numeric convention.  As you point
> out, having multiple conventions is definitely a bad idea.

Even having just one convention might be a problem if the convention
was bad -- complicated, irregular, inconsistent.  I think Python's
arrangement here is quite good.


Alex




More information about the Python-list mailing list