Slice objects with negative increment
Alex Martelli
aleax at aleax.it
Tue Apr 30 10:47:40 EDT 2002
Paul Hughett wrote:
> Alex Martelli <aleax at aleax.it> wrote:
> : 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! [Use the same convention as Numeric]
>
> Okay, I've looked up the convention for Numeric, but the description
> isn't entirely clear in the case of negative increments. It states that
> the default values for start and stop when the increment is negative are
> "the beginning" and "the end" of the axis. Suppose that the axis has
> n elements. Does ::-k default to
>
> n:0:-k which refers to element n, which doesn't exist
> (n-1):0:-k which skips element 0
> n:-1:-k which refers to element n, and apparently to -1 => n-1,
> or
> (n-1):-1:-k which is not generally the reversal of 0:n:k for k > 1
>>> r=Numeric.array(range(13))
>>> r
array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
>>> r[::-1]
array([12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0])
>>> r[::-2]
array([12, 10, 8, 6, 4, 2, 0])
>>> r[::-3]
array([12, 9, 6, 3, 0])
>>>
> By the way, I don't see anything in "Numerical Python" about the
> meaning of a negative start or stop. Do they follow the usual Python
> convention of meaning the nth element from the end?
>>> r[-3::]
array([10, 11, 12])
>>> r[-3::-1]
array([10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0])
>>>
Alex
More information about the Python-list
mailing list