slice indices (RE: More random python observations from a perl programmer)

Tim Peters tim_one at email.msn.com
Fri Aug 20 01:34:57 EDT 1999


[tchrist]
> > GOTCHA: (medium)
> >     All ranges are up to but *not including* that point.  So range(3)
> >     is the list [0,1,2].  This is also true in slices, which is the
> >     real gotcha part.  A slide t[2:5] does not include t[5] in it.

[Jan Decaluwe]
> I always found this very strange. However, in practical use it turns
> out to be often quite natural, for example:
>    a[:5] returns 5 elements.

More generally, seq[i:j] contains j-i elements (assuming 0 <= i <= j).

> Exactly the same approach is used by the containers in C++'s STL
> library, so I guess there must be some good theoretical arguments
> also.

It's not theory, it's practical <wink>:  learn to view indices as pointing
*between* elements, and it all makes perfect sense at once.  Where does

    x.insert(5, thing)

insert thing?  If you view indices as pointing *at* elements, it's unclear
whether "thing" ends up to the left or the right of x[5].  But view 5 as
pointing *between* adjacent elements, and it's obvious.

Ditto for sequence[i:j], and so on.  Viewing that as "the slice beginning at
i and ending before j" is hopelessly convoluted.

True story:  Fortran was my first high-level language.  When I learned C, I
looked at e.g.

int c[10];

and wondered why on earth C declared arrays with a number one higher than
the largest legit index!  It was almost a year before it dawned on me that
it was meant to be viewed as declaring the total number of elements.

Python's flavor of slice notation will look just as obvious and natural when
it "clicks" for you.

otoh-i-still-don't-know-where-to-put-the-damned-"const"s-ly y'rs  - tim






More information about the Python-list mailing list