Slice objects with negative increment

Alex Martelli aleax at aleax.it
Wed May 1 15:57:22 EDT 2002


Paul Hughett wrote:
        ...
> : 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.  [details omitted]
> 
> Perhaps, but they give some results that I find anomalous.  Consider this

You'll agree that the use of negative indices aliased to nonnegative ones,
used also in indexing, is a convenience that cannot be given up.  Given 
that, I doubt one can construct rules, analogous for slice, range etc, that
can avoid any 'minuscule' "special-case" such as the one below.

> mini-problem:  Given i and j such that j > i >= 0, write a snippet of
> code to construct a slice object that selects elements j-1, j-2, ..., i.
> If I understand the interpretation of slices correctly, i = 0 must
> be treated as a special case and the code must look something like
> 
>    if i == 0 :
>       slc = slice(j, None, -1)
>    else :
>       slc = slice(j, i, -1)

No, slice(j,i,-1) works for any j and i meeting your constraints, but it
gives elements j, j-1, ..., i+1, not the ones you require.  In Python,
any range and the like is always first-bound-included, last-bound-
excluded (as A. Koenig suggested even for C back in the '80s).

You do need to special-case your request if you don't know the length of the
sequences involved, because then you don't know the exact rule by which
positive and negative indices are mapped.  I.e., you can't mix negative and
positive indices unless you know how they correspond (thus, unless you
know the sequence's length).


> : 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.
> 
> I'm less convinced of that, in light of the example just given.
> Having to treat element zero as a special case could come as a nasty
> surprise to some programmer.

No doubt, if that programmer knows so little Python as to ignore that
-1 is a valid index and indicates the last one of the sequence.  Without
that knowledge, the consequence that i-1 is also a valid index for i==0,
but then it's at the end, not "before the start" as it would be if negative
indices weren't mapped that way.

This meaning of a "-1" index, however, is so often required in Python,
that most learn it very early in their study of the language.  That being
so, it's hardly surprising that some programmer who tries to use
reasonably advanced constructs (generic slice objects prepared w/o
knowledge of the lengths of the sequences to which they will apply)
without a grasp of elementary ones (negative indices) is setting himself
(or herself) up for nasty surprises.


Alex




More information about the Python-list mailing list