question about slicing with a step length

André andre.roberge at gmail.com
Wed Mar 8 21:37:09 EST 2006


Steven D'Aprano wrote:
> John Salerno wrote:
>
> > Given:
> >
> > numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
> >
> > can someone explain to me why
> >
> > numbers[10:0:-2] results in [10, 8, 6, 4, 2]?
>
> I think the documentation is misleading/incomplete when
> it comes to negative strides for extended slices.

Agreed!

[snip...]
>
> The indices actually selected are:
>
> 9, 7, 5, 3, 1
>
> at which point I give up and throw my hands in the air
> and promise never to use negative strides with extended
> slices.
>
!!!  Agreed!

I found this which seems an appropriate description:
"""
An extended slice of list x of length n in the form x[j:k:i] selects
every i-th element starting with and including the element at index j
and ending with but not including the element at index k. When either
index is negative, the value of n is added to it before any further
processing occurs. When either index is missing or lies outside of the
list bounds, the minimum or maximum inclusive index is used
automatically.
"""
source: https://trove.homeip.net/ExtendedSlices
André

> -- 
> Steven.




More information about the Python-list mailing list