Slice objects with negative increment

Huaiyu Zhu huaiyu at gauss.almadan.ibm.com
Tue Apr 30 20:34:46 EDT 2002


Paul Hughett <hughett at mercur.uphs.upenn.edu> wrote:
>Alex Martelli <aleax at aleax.it> wrote:
>
>:> Alex Martelli <aleax at aleax.it> wrote:
>
>:>>> r=Numeric.array(range(13))
>
>:>>> r[-3::]
>: array([10, 11, 12])
>:>>> r[-3::-1]
>: array([10,  9,  8,  7,  6,  5,  4,  3,  2,  1,  0])
>:>>>
>
>Hmm.  Is the value of r[-1:-1:-1] equal to array([12, 11, 10, 9, 8, 7,
>6, 5, 4, 3, 2, 1, 0]) or to an empty array?  It could plausibly be
>either, depending on whether the middle -1 is interpreted as a lower
>limit or as 1 from the end.

Some quick experiments:

>>> r = arange (7)
>>> r[::-1]
array([6, 5, 4, 3, 2, 1, 0])
>>> r[5::-1]
array([5, 4, 3, 2, 1, 0])
>>> r[5:2:-1]
array([5, 4, 3])
>>> r[:2:-1]
array([6, 5, 4, 3])
>>> r[7:2:-1]
array([0, 6, 5, 4, 3])
>>> r[17:2:-1]
array([0, 6, 5, 4, 3])
>>> r[17:-1:-1]
array([0])
>>> r[:-1:-1]
zeros((0,), 'l')
>>> r[:-11:-1]
array([6, 5, 4, 3, 2, 1, 0])
>>> r[:-3:-1]
array([6, 5])
>>> r[:-5:-1]
array([6, 5, 4, 3])
>>> r[-2:-5:-1]
array([5, 4, 3])
>>> 

Summarization of the rules left as an exercise to the reader.  :-)
When the bounds are out of range, the rules are not very obvious, in fact.

Huaiyu



More information about the Python-list mailing list