Zero-Based Indexing

A zero-based index counts how many steps an element is from the start of a sequence.

Source
Anbloq
Language
English
Created
Updated
Chapters
4
Reading time
1 min
In this article4 chapters
  1. Compute the ends from the length
  2. Translate a displayed rank
  3. Distinguish positions, displayed numbers and counts
  4. Check the midpoint using a length different from the largest index

Compute the ends from the length

A sequence with four entries has offsets 0, 1, 2, and 3. Offset zero is the first entry. The length is therefore the first offset beyond the end. This explains a common loop boundary error.

Translate a displayed rank

If a user selects item 3 from a one-based menu, subtract one to find sequence offset 2. Validate that the menu choice is between 1 and the length first. A value of zero could turn into a valid negative index under some languages' indexing rules.[1]

Distinguish positions, displayed numbers and counts

In a five-line editor buffer, internal positions run from zero to four. A diagnostic that refers to line five in the interface has to convert it to position four before accessing the buffer. Convert labels at the entry point and keep positions in one convention inside the operation. Compare the first and last diagnostic with the underlying line. A count of zero lines is valid even though position zero is invalid for an empty buffer. See sequence slice boundaries for how an empty extent is represented.

Check the midpoint using a length different from the largest index

For a buffer of length eight under zero-based numbering, positions three and four straddle the midpoint. Dividing the length by two with integer division gives four, the start of the right half. Walking both halves should cover exactly eight entries. A loop bounded by seven as an exclusive end misses position seven. Testing even and odd lengths exposes different boundary errors. See off-by-one errors in loops.

References

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