Slice objects with negative increment

Alex Martelli aleax at aleax.it
Thu May 2 06:10:48 EDT 2002


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)
        ...
> It is necessary to special-case it even if I do know the length of the
> sequence involved.  

Why ever would it be?  slice(j-L-1, i-L-1, -1) works per your stated
constraints and requirements for a sequence of length L, obviously.

> 0.  I'm a careful programmer and know the -n convention for indices,

Then maybe you're noticing something I'm not, given that this seems
so obvious to me while you keep insisting some specialcasing is needed.

Please instruct me.  Given L >= j (a constraint now added by knowing
the length L of the sequence involved), isn't it obvious that j-L-1
is < 0?  This would appear to me to be a pretty simple disequation
manipulation.  And thus since i<j, i-L-1 also < 0, right?  And so,
we are only dealing with negative indices and no special-casing nor
precaution is needed -- it seems to me.  What am I missing, o
careful programmer who knows the -n convention for indices?  Thanks!


Alex




More information about the Python-list mailing list