Comment

Comment by ot

As Guido says, 1-based indexes basically force closed ranges, so that [1, length] is the full array.

One thing that annoys me about closed ranges (and it's not much talked about) is that it is impossible to express the empty range: in python [i:i] is an empty range, while closed ranges always contain at least one element. That makes closed ranges strictly less expressive than half-open ranges, making often necessary to write special cases for zero-length.

For example when you want to split an array or a string at a given position i, the partitions will always be a[:i] and a[i:] even if one of the two is empty.

The other big issue, as many comment, is that the arithmetic to index multi-dimensional arrays is cumbersome with 1-based indexing: for example if I is a 2d image in row-major, the element (x, y) is at position I[(y - 1) * width + x] instead of I[y * width + x]. It's very easy to do off-by-one errors this way.

EDIT: adding this just to try some ASCII art :)

I think that the preference about 0-based and 1-based indexing boils down to how you reason about indexes.

I (0-indexing) think of them as the following:

      |-|-|-|...|-|
      ^           ^
    first   past-the-end
   position
that is, the index is where the element begins. This way there is a special endpoint, the "past-the-end", where the an appended element would begin. In particular, an empty array has both first and last endpoint equal to 0.

I believe that people who favor 1-based indexing think like this

      |-|-|-|...|-|
       ^         ^
    first      last
   element    element
that is, in the ordinal way, i is the i-th element.
parent ot 13 years ago

Discussion

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton