Why Python does *SLICING* the way it does??

Torsten Bronger bronger at physik.rwth-aachen.de
Wed Apr 20 08:14:57 EDT 2005


Hallöchen!

nde at no.spam.org (Nick Efford) writes:

> seberino at spawar.navy.mil <seberino at spawar.navy.mil> wrote:
>> Many people I know ask why Python does slicing the way it does.....
>
>> Can anyone /please/ give me a good defense/justification???
>
>> I'm referring to why mystring[:4] gives me elements 0, 1, 2 and 3
>> but *NOT* mystring[4] (5th element).
>
> mystring[:4] can be read as "the first four characters of
> mystring".  If it included mystring[4], you'd have to read it as
> "the first five characters of mystring", which wouldn't match the
> appearance of '4' in the slice.
>
> [...]
>
> It all makes perfect sense when you look at it this way!

Well, also in my experience every variant has its warts.  You'll
never avoid the "i+1" or "i-1" expressions in your indices or loops
(or your mind ;).

It's interesting to muse about a language that starts at "1" for all
arrays and strings, as some more or less obsolete languages do.  I
think this is more intuitive, since most people (including
mathematicians) start counting at "1".  The reason for starting at
"0" is easier memory address calculation, so nothing for really high
level languages.

But most programmers are used to do it the Python (and most other
languages) way, so this opportunity has been missed for good.

Tschö,
Torsten.

-- 
Torsten Bronger, aquisgrana, europa vetus



More information about the Python-list mailing list