Slice objects with negative increment

Paul Hughett hughett at mercur.uphs.upenn.edu
Mon Apr 29 17:09:07 EDT 2002


I am writing a Python extension in which it has become useful to
define slice objects that run backwards (i.e. that have a negative
increment) and want to use the existing convention, if any, for
such objects.  But I don't recall ever seeing such a convention.

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

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.

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

Any comments?


Paul Hughett



More information about the Python-list mailing list