Slice objects with negative increment

Paul Hughett hughett at mercur.uphs.upenn.edu
Wed May 1 18:19:46 EDT 2002


Alex Martelli <aleax at aleax.it> wrote:
: Paul Hughett wrote:

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

Oops.  To solve the stated problem, my code should have been:

    if i == 0 :
       slc = slice(j, None, -1)
    else :
       slc = slice(j, i-1, -1)


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

It is necessary to special-case it even if I do know the length of the
sequence involved.  My discontent is that the meaning of i-1 as the
stop value changes abruptly and unobviously when i changes from 1 to
0.  I'm a careful programmer and know the -n convention for indices,
but I would probably have written slice(j, i-1, -1) and been bitten by
it anyway, since what I'm trying to do has nothing to do with indices
relative to the end of the sequence.  The principle of least
astonishment has been violated here, at least in my eyes.  If I adopt
the negative index convention in my extension, then I feel I need to
add a note to my documentation explaining this little gotcha of that
convention.


Paul Hughett



More information about the Python-list mailing list