Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
356 views
in Technique[技术] by (71.8m points)

python - Why are slice and range upper-bound exclusive?

Disclaimer: I am not asking if the upper-bound stopargument of slice()and range() is exclusive or how to use these functions.

Calls to the rangeand slicefunctions, as well as the slice notation [start:stop] all refer to sets of integers.

range([start], stop[, step])
slice([start], stop[, step])

In all these, the stop integer is excluded.

I am wondering why the language is designed this way.

Is it to make stopequal to the number of elements in the represented integer set when start equals 0 or is omitted?

Is it to have:

for i in range(start, stop):

look like the following C code?

for (i = start ; i < stop; i++) {
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:] equals s.

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] is 2.

I think we can assume that the range functions act the same for consistency.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...