Negative Indices in Python Sequences

A negative index identifies a position relative to the sequence's end when the sequence supports that convention.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Translate an example
  2. Check the extreme inputs
  3. Convert negative positions with a visible trace
  4. Separate ordinary indexing from slice clipping

Translate an example

For ["a", "b", "c", "d"], index minus one is d and index minus four is a. Add the length to a negative index to find the equivalent nonnegative offset for built-in sequences. Zero-based indexing applies to that translated value.

Check the extreme inputs

Index minus five is outside a four-item sequence. An empty sequence has no last item, so minus one also fails there. Validate a user-supplied nonnegative choice before subtracting one. Boundary cases can reveal accidental use of the negative convention.[1]

Convert negative positions with a visible trace

In a Python list of four readings, index minus one means position three and minus four means position zero. An index of minus five is outside the supported range. The formula \(i_{\mathrm{normalized}}=n+i\) works for valid negative indices because the length counts the steps from the beginning to the exclusive end. On an empty list there is no last item, so even minus one fails. See zero-based indexing to keep the range of normalized positions clear.

Separate ordinary indexing from slice clipping

For [10, 20, 30, 40], using [-10] raises an index error, while [-10:2] returns [10, 20] due to Python's clipping of slice bounds. This difference can hide a defect if code expecting to retrieve one required entry switches to a slice and treats the resulting empty list as an ordinary answer. Test overshooting at both ends and on the empty list. See slicing versus indexing.

References

  1. Python Software Foundation, Python Standard Library: Built-in Types ↩