[Solved] Why does this work, I am slicing 1 past max index and not getting an error?


It’s in the spec. Having low or high equal to the length is allowed.

For arrays or strings, the indices are in range if 0 <= low <= high <= len(a), otherwise they are out of range.

As to “why is this not an error”: you can visualize the slicing operation as cutting between the elements. Like this:

│   a   t   t   r   i   b   u   t   e   =    │
│ ↑   ↑   ↑   ↑   ↑   ↑   ↑   ↑   ↑   ↑   ↑  │
│ 0   1   2   3   4   5   6   7   8   9   10 │

Technically slice point 10 is still within bounds, but it has no elements after it. That’s why [10:] results in an empty string (that, or because there are no elements between low and high). This works the same way in ruby, for example. Maybe other languages too.

0

solved Why does this work, I am slicing 1 past max index and not getting an error?