negative stride list slices

Peter Hansen peter at
Thu Sep 2 01:21:06 CEST 2004

Julio Oña wrote:

> On Wed, 01 Sep 2004 18:05:22 -0400, Peter Hansen <peter at> wrote:
>>please explain *which* elements are being listed in reverse
>>order, referring to the index value -3 and the elided
>>index value.  
> Well in the case [:-3:-1] I think this is what is happening
>   - revers the list 
>   - this left with [0:2] (remember  [-3:] returns 2 characters only
> in the case [-1:-2:-1]
>   - revers the string 'Apleh'
>   - this left with [:1] (this is tricky but -1 is equivalent to 0 as
> -2 is to 1, remember you are counting backwards from the end)
> The problem is the mening of -1 when reversing the list. The slice is
> closed in the lower side and open in the upper one. When reversing the
> list the lower end is open and no close as with positive step.
> Any comments?

Okay, so let me see how this looks with the previous diagram.

  | H | e | l | p | A |
  0   1   2   3   4   5
-5  -4  -3  -2  -1

But that only works for the forward or positive step case.
With a negative/reverse step, you first have to reverse
the string:

  | A | p | l | e | H |
-1  -2  -3  -4  -5  -6

And now you're in effect going from the start (i.e. the
missing value before the colon) to the -3 point.

Thus 'Ap'.

I don't find it at all intuitive, and certainly the existing
diagram needs to be updated if this is really how it works,
but at least you have an explanation that corresponds to the
values, so thank you.

It does seem very odd that the step of -1 in effect changes
the normal meaning or position of the slice indices, by
first reversing the string.  I'm guessing that this is
necessary because any other interpretation leads to even
worse situations than the confusion this inspires, but
perhaps that's not true.

I would have found either 'Apl' or 'eH' more intuitive...


More information about the Python-list mailing list