Why Python does *SLICING* the way it does??
Nick Efford
nde at no.spam.org
Wed Apr 20 07:52:40 EDT 2005
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.
Given another slice like mystring[2:4], you know instantly by
looking at the slice indices that this contains 4-2 = 2 characters
from the original string. If the last index were included in the
slice, you'd have to remember to add 1 to get the number of
characters in the sliced string.
It all makes perfect sense when you look at it this way!
Nick
More information about the Python-list
mailing list