Skip to main content
The 2026 Annual Developer Survey is live— take the Survey today!
edited title
Link
smci

Why are Python's slice and range upper-bound exclusive?

edit for clarity, to remove forum-mode discussion/noise, and shorten; add see-also
Source Link
Karl Knechtel

Disclaimer: I am not asking if the upper-boundknow that when I use stoprange([start], stop[, step])argument of or slice([start], stop[, step])and, the range()stop value is exclusive or hownot included to use these functionsin the range or slice.

Calls to theBut rangeandwhy does it work this way?

Is it so that e.g. a slicerange(0, x)functions, as well as the slice notation or [start:stop]range(x) all refer to sets of integers.

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

In all these, thewill contain stopx integer is excluded.

I am wondering why the language is designed this way.many elements?

Is it to makefor parallelism with the C for loop idiom, i.e. so that for i in range(start, stop):equal to the number of elements in the represented integer set when superficially resembles for (i = start ; i < stop; i++) { equals 0 or is omitted?

Is it to have:

for i in range(start, stop):
 

look like the following C code?See also Loop backwards using indices for a case study: setting the stop and step values properly can be a bit tricky when trying to get values in descending order.

for (i = start ; i < stop; i++) {

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++) {

I know that when I use range([start], stop[, step]) or slice([start], stop[, step]), the stop value is not included in the range or slice.

But why does it work this way?

Is it so that e.g. a range(0, x) or range(x) will contain x many elements?

Is it for parallelism with the C for loop idiom, i.e. so that for i in range(start, stop): superficially resembles for (i = start ; i < stop; i++) {?

 

See also Loop backwards using indices for a case study: setting the stop and step values properly can be a bit tricky when trying to get values in descending order.

rm tag from title
Link
svick

Python: why Why are slice and range upper-bound exclusive?

edited tags
Link
ecatmur
Loading
Source Link
wap26
Loading
lang-py