Why are slice and range upper-bound exclusive?
Solution 1:
The documentation implies this has a few useful properties:
word[:2] # The first two characters
word[2:] # Everything except the first two characters
Here’s a useful invariant of slice operations:
s[:i] + s[i:]
equalss
.For non-negative indices, the length of a slice is the difference of the indices, if both are within bounds. For example, the length of
word[1:3]
is2
.
I think we can assume that the range functions act the same for consistency.
Solution 2:
Here's the opinion of some Google+ user:
[...] 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:].
Google+ is closed, so link doesn't work anymore. Spoiler alert: that was Guido van Rossum.