[Python-ideas] Range and slice syntax

Chris Angelico rosuav at gmail.com
Tue Nov 13 13:18:54 EST 2018


On Wed, Nov 14, 2018 at 5:14 AM David Allemang <allemang.d at gmail.com> wrote:
>
> That is not what slice.indices does. Per help(slice.indices) -
>
> "S.indices(len) -> (start, stop, stride)
>
> "Assuming a sequence of length len, calculate the start and stop indices, and the stride length of the extended slice described by S. Out of bounds indices are clipped in a manner consistent with handling of normal slices.
>
> Essentially, it returns (S.start, len, S.step), with start and stop adjusted to prevent out-of-bounds indices.

And to handle negative indexing.

>>> slice(1,-1).indices(100)
(1, 99, 1)

A range from 1 to -1 doesn't make sense (or rather, it's an empty
range), but a slice from 1 to -1 will exclude the first and last of
any sequence.

ChrisA


More information about the Python-ideas mailing list