Tutorial creates confusion about slices

Ant antroy at gmail.com
Wed Apr 25 12:14:38 CEST 2007

On Apr 23, 1:38 pm, Antoon Pardon <apar... at forel.vub.ac.be> wrote:
> The following is part of the explanation on slices in the
> tutorial:
> The best way to remember how slices work is to think of the indices as
>   +---+---+---+---+---+
>   | H | e | l | p | A |
>   +---+---+---+---+---+
>   0   1   2   3   4   5
>  -5  -4  -3  -2  -1

For a tutorial this is sound advice. A tutorial is designed to give
readers an easy intro to a topic, which is what this achieves. At this
stage the target audience has no idea that extended slices even exist,
let alone that you can use negative indices with them.

> This is all very well with a simple slice like:
>   "HelpA"[2:4]    =>     "lp"
> But it give the wrong idea when using the following extended slice:
>   "HelpA"[4:2:-1]   =>   "Ap"

But that is fine. Extended slice notation (let alone using negative
indices) is beyond the scope of the tutorial. Once you start to
experiment with extended slices, it is time to look beyond the
simplified tutorial information, and to the official documentation in
the Library and Language references. The library docs (http://
docs.python.org/lib/typesseq.html) say this:

(5) The slice of s from i to j with step k is defined as the sequence
of items with index x = i + n*k such that 0 <= n < (j-i/k)

Which is exactly how it works, and describes exactly why your extended
slice example works as it does.

More information about the Python-list mailing list