Frage

What is the advantage of making the end index in the Python slice syntax yield characters from "start" to "end-1"?

That is, I understand that if a = [2,3,4], then a[0:2] yields [2,3], and a[1:3] yields [3,4]. I see the intuitive meaning of "the first 2 characters" for the a[0:2] case, but I fail to see how it's clear for other cases without 0 as the start index. It would seem more intuitive to just make the syntax from "start" to "end", instead.

Or are there advantages to this syntax that I'm not seeing?

War es hilfreich?

Lösung

Because Guido made it that way.

Using 0-based indexing, half-open intervals, and suitable defaults (as Python ended up having), they are beautiful: a[:n] and a[i:i+n]; the former is long for a[0:n].

But how does the index:length convention work out for other use cases? TBH this is where my memory gets fuzzy, but I think I was swayed by the elegance of half-open intervals. Especially the invariant that when two slices are adjacent, the first slice's end index is the second slice's start index is just too beautiful to ignore. For example, suppose you split a string into three parts at indices i and j -- the parts would be a[:i], a[i:j], and a[j:].

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top