This idiom can be justified using modular arithmetic. We can think of indices as referring to a cell in a list obtained by walking forward i
elements. -1
referring to the last element of the list is a natural generalization of this, since we arrive at the last element in the list if we walk backwards one step from the start of the list.
For any list xs
and index i
positive or negative, the expression
xs[i]
will either have the same value as the expression below or produce an IndexError
:
xs[i % len(xs)]
The index of the last element is -1 + len(xs)
which is congruent to -1
mod len(xs)
. For example, in an array of length 12, the canonical index of the last element is 11. 11 is congruent to -1 mod 12.
In Python, though, arrays are more often used as linear data structures than circular ones, so indices larger than -1 + len(xs)
or smaller than -len(xs)
are out of bounds since there's seldom a need for them and the effects would be really counterintuitive if the size of the array ever changed.