Mailing List Archive

slice indices (RE: More random python observations from a perl programmer)
[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
slice indices (RE: More random python observations from a perl programmer) [ In reply to ]
In article <001201beeacd$bd088500$712d2399@tim>, "Tim Peters"
<tim_one@email.msn.com> wrote:

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

My reaction to slicing being "starting from...not including" was
"OK...I'll do it that way." It didn't (and doesn't) seem like a big deal.

--John

--
John W. Baxter Port Ludlow, WA USA jwb@olympus.net
slice indices (RE: More random python observations from a perl programmer) [ In reply to ]
[John W. Baxter]
> My reaction to slicing being "starting from...not including" was
> "OK...I'll do it that way." It didn't (and doesn't) seem like a
> big deal.

Then you settled for coping when you could be understanding.

unlike-the-microsoft-api-this-actually-makes-sense<wink>-ly y'rs - tim