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

James Carroll mrmaple at gmail.com
Wed Apr 20 13:58:18 EDT 2005


If you have five elements, numbered 0,1,2,3,4  and you ask for the
elements starting with the first one, and so on for the length you
would have [0:length].  So [0:5] gives you elemets 0,1,2,3,4.   Think
of the weirdess if you had to ask for [0:length-1] to get length
elements...

One based 1...  n  are what I call _counting numbers_
Zero based 0...  n-1 are the _indexes_ (offsets) into the collection. 
The first element is at offset 0.

It is a little weired that slicing does [index: count] instead of
[index:index] or [count:count] I agree, but python really does just
flow wonderfully once you see how clean code is that's written [index:
count].

In C++ the STL also has the idea that there's an 'end()' iterator that
is really one element past the end of your container.  It makes things
flow really well there too.  All code interates up to but not
including the last element you specify. always.

-Jim



On 19 Apr 2005 22:58:49 -0700, 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).
> 
> Many people don't like idea that 5th element is not invited.
> 
> (BTW, yes I'm aware of the explanation where slicing
> is shown to involve slices _between_ elements.  This
> doesn't explain why this is *best* way to do it.)
> 
> Chris
> 
> --
> http://mail.python.org/mailman/listinfo/python-list
> 
>



More information about the Python-list mailing list