[Python-ideas] List Revolution

Nick Coghlan ncoghlan at gmail.com
Sun Sep 11 03:51:14 CEST 2011


On Sun, Sep 11, 2011 at 10:37 AM, Steven D'Aprano <steve at pearwood.info> wrote:
> 0-based indexes are useful for some tasks, and less useful for other tasks.
> In my experience, I find that 0-based indexing is more useful most of the
> time: it leads to fewer off-by-one errors.
>
> 1-based indexes are particularly well-suited for programming languages using
> a natural language metaphor, usually aimed at non-programmers. Examples
> include Xion, Applescript, and Inform-7.

Indeed, the concepts of half-open ranges and 0-based indexing go hand
in hand (as described in the EWD article), and it ties directly in to
the notion of *index arithmetic*.

A case that illustrates this nicely is that of partitioning a
sequence. Suppose we want the first 5 items in one subsequence and the
rest in another. This is easy to write, and requires no adjustments to
the numbers:

  head = seq[:5]
  assert len(head) == 5
  tail = seq[5:]
  assert len(tail) == len(seq) - 5

Zero based indexing (in conjunction with half-open ranges) makes the
arithmetic work out nicely, and, in practice, that turns out to be
important when it comes to writing correct programs.

However, it comes at the cost of breaking the intuitive mapping to the
counting numbers: the first item is at offset 0, the second is at
offset 1, etc. This is a definite downside, but the collective
judgment of many language designers is that the reduction in
off-by-one errors when manipulating indices is worth the additional
difficulty in learning the language for programming novices.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia



More information about the Python-ideas mailing list