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

Discussão em 'Python' iniciado por Stack, Setembro 15, 2024.

  1. Stack

    Stack Membro Participativo

    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.

    Continue reading...

Compartilhe esta Página