# question about slicing with a step length

Steven D'Aprano steve at REMOVEMEcyber.com.au
Thu Mar 9 02:27:43 CET 2006

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

The relevent sections are here:

http://www.python.org/doc/2.3.5/ref/types.html

[quote]
Some sequences also support "extended slicing" with a
third "step" parameter: a[i:j:k] selects all items of a
with index x where x = i + n*k, n >= 0 and i <= x < j.
[end quote]

and from http://www.python.org/doc/2.3.5/ref/slicings.html

[quote]
It is not an error if i or j lie outside the range of
valid indexes (such items don't exist so they aren't
selected).
[end quote]

The documentation suggests that, given a slice
[10:0:-2], Python looks up indices:

10 + 0*-2, 10 + 1*-2, 10 + 2*-2, ...

or 10, 8, 6, 4, 2, 0, ...

but since *none* of these indices is within the limits
10 <= x and x < 0, the documentation suggests that
the result should be the empty list.

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.

--
Steven.

```