MathCurvesSurfacesWallpaper GroupsGallerySoftwarePOV-Ray
ProgramingLinuxPerl PythonHTMLCSSJavaScriptPHPJavaEmacsUnicode ♥
Web Hosting by 1&1

Language Design: Should Array Index Start at 0 or 1?

Xah Lee,

should array index start at 0 or 1?

the eminent computer scientist Edsger W Dijkstra (EWD) thinks it should start at 0. See: 〔Why numbering should start at zero By Edsger W Dijkstra. @ www.cs.utexas.edu…〕. But it's not really convincing.

Most popular langs start with 0. ⁖ C, Perl, Python, Ruby, Java, Emacs Lisp, JavaScript.

those starting at 1 include: FORTRAN, SASL, MATLAB, Smalltalk, Lua, Julia, Mathematica.

Seems most number crunching languages start at 1. New interesting one is Julia. Mathematica is a special case. It starts at 1, but actually, 0 refers to the head of expression, so it's all consistent.

Python follows EWD's recommendation to a tee. It start at 0, and the ending index does not include the element. Example:

# -*- coding: utf-8 -*-
# python3

a = list(range(1,4))
print(a)         # [1, 2, 3]. most annoying.

b = ["a", "b", "c"]
print(b[0:1])                   # ['a']

Python's way is the most painful to work with.

most other langs, even they start at 0, but a ending index usually is inclusive. For example, here's Perl.

# -*- coding: utf-8 -*-
# perl

use Data::Dumper;

@a = ('a','b','c');

@b = @a[0..1];

print Dumper(\@b);              # ['a', 'b']

in my view, it should start at 1, and ending index should be inclusive. Because that's just easier to work with. Also, when you have nested array, starting at 1 is much easier to work with. Nested array is heavily used in math, for marix, tensor, tree, no wonder most number crunchers start at 1.

what's your experience?

blog comments powered by Disqus