pythonlanguage-designslice

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


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.


Solution

  • 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.