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

Ron radam2 at tampabay.rr.com
Thu Apr 21 04:03:34 EDT 2005


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
> 

Hi Chris,

What I've found is foreword slicing with positive stepping is very 
convenient for a lot of things. :-)

But when you start trying to use reverse steps, it can get tricky.

There are actually 4 different ways to slice and dice. So we have a 
pretty good choice. So the trick is to match the slice method to what 
you need, and also use the correct index's for that method.


Where s = 'abcd'
With s[i,j]

Foreword slices index, forward steps
     a,  b,  c,  d
i=  0,  1,  2,  3
j=  1,  2,  3,  4

s[0,4] = 'abcd'
s[1,3] = 'bc'

Foreword slice index (-steps)
     a,  b,  c,  d
i=  0,  1,  2,  3
j= -5, -4, -3, -2

s[3,-5] = 'dcba'
s[2,-4] = 'cb'

Reverse slice index (+steps)
     a,  b,  c,  d
i= -4, -3, -2, -1
j=  1,  2,  3,  4

s[-4,4] = 'abcd'
s[-3,3] = 'bc'

Reverse slice index (-steps)
     a,  b,  c,  d
i= -4, -3, -2, -1
j= -5, -4, -3, -2

s[-1,-5] = 'dcba'
s[-2,-4] = 'cb'


(Maybe this could be made a little more symetrical for Python 3000?)

Cheers,
Ron_Adam



More information about the Python-list mailing list