Slice objects with negative increment

Alex Martelli aleax at aleax.it
Mon Apr 29 17:56:15 EDT 2002


Paul Hughett wrote:
        ...
> Hence my question: Is there an established meaning within Python for
> slice objects with a negative increment?  E.g. slice(1, 10, -2) ?

Sure!

>>> import Numeric
>>> x=Numeric.array(range(20))
>>> print x[1:10:-2]
zeros((0,), 'l')
>>> print x[10:1:-2]
[10  8  6  4  2]

slice(1,10,-2) is exactly what x.__getitem__ gets in the first case (and
slice(10,1,-2) in the second case).  In the first case, since the step is < 
0 and the start index is already < the stop index, an empty array comes
out -- just as it would for x[10:1:2], of course (or x[10:1] for that 
matter).  In the second case, since here the start index is >= the stop
index, then the usual rule (start, start+step, start+2*step) also applies.


> If not, then I am inclined to define slice(i,j,-n) to mean the same as
> reverse(slice(i,j,n)); then slice(1,10,-2) would mean (9, 7, 5, 3, 1).
> This seems simpler for users than the alternatives that I've considered.

Sorry, but I disagree.  Even if your users aren't used to Numeric's slice
behavior, it's exactly what one would expect from other analogous
Python behaviors, e.g.:

>>> range(1,10,-2)
[]
>>> range(10,1,-2)
[10, 8, 6, 4, 2]

> The primary use case that I have in mind is a multi-dimensional array
> type in which it may be necessary to access a given dimension in
> either the forward or backward direction.  Under the proposed rule,
> elements i up to j in the forward direction would be i:j:1 or just
> i:j, while the same elements in the reverse direction would be i:j:-1.

Under Python's rule, they're j:i:-1 instead -- much better, imho.

> Even-numbered elements up to j in the forward direction would be 0:j:2
> and in the reverse direction would be 0:j:-2.

Wouldn't j:0:-2 be better?

> Any comments?

Take care not to let apparent "convenience" overrule simplicity,
regularity, and universal application of rules and analogies.  I think
that, even more than syntax cleanliness, this is what puts Python
apart from Perl, which always put great stock in "convenience".


Alex




More information about the Python-list mailing list