Tutorial creates confusion about slices

Antoon Pardon apardon at forel.vub.ac.be
Tue Apr 24 02:42:49 EDT 2007


On 2007-04-23, Hamilton, William <whamil1 at entergy.com> wrote:
>> -----Original Message-----
>> From: python-list-bounces+whamil1=entergy.com at python.org
> [mailto:python-
>> list-bounces+whamil1=entergy.com at python.org] On Behalf Of Antoon
> Pardon
>> Sent: Monday, April 23, 2007 7:38 AM
>> To: python-list at python.org
>> Subject: Tutorial creates confusion about slices
>> 
>> 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
>> pointing between characters, with the left edge of the first character
>> numbered 0. Then the right edge of the last character of a string of n
>> characters has index n, for example:
>> 
>>   +---+---+---+---+---+
>>   | H | e | l | p | A |
>>   +---+---+---+---+---+
>>   0   1   2   3   4   5
>>  -5  -4  -3  -2  -1
>> 
>> 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"
>> 
>> So this doesn't result in the reverse of the previous expression while
>> the explanation above suggest it does.
>  
> It makes sense if you recognize that the negative step value also flips
> which "side" the index is on.  
>
>    +---+---+---+---+---+
>    | H | e | l | p | A |
>    +---+---+---+---+---+
>        0   1   2   3   4
>   -6  -5  -4  -3  -2  -1

That is a possibility. I just don't think we can expect from people
reading the tutorial to recognize this. So if we conclude this is
the correct explanation it should be clearly explained in the
tutorial.

-- 
Antoon Pardon



More information about the Python-list mailing list