Coding

Array Indexing in Programming: Why Arrays Start at 0

Array indexing in programming means reading or writing an element by its position, and in most common languages the first position is index 0. An array of n elements therefore has valid indexes 0 to n - 1.

The examples below use C, Python and JavaScript, because their documentation states the rule explicitly.

How array indexing works

You write the array name followed by the index in square brackets. The index selects one element:

/* C */
int a[3] = {10, 20, 30};
a[0];   /* 10, the first element */
a[2];   /* 30, the last element */
# Python
s = [10, 20, 30]
s[0]    # 10
s[2]    # 30
// JavaScript
const fruits = ["Apple", "Banana"];
fruits[0];                  // "Apple"
fruits[fruits.length - 1];  // "Banana"

The Python documentation describes s[i] as the "ith item of s, origin 0". MDN says JavaScript arrays are zero-indexed: the first element is at index 0, and the last is at the value of length minus 1. Both statements match the C behavior shown above.

Why arrays start at 0

There are two reasons, and they support each other: how the computer finds an element, and which numbering makes ranges easiest to write.

The offset reason

C defines E1[E2] as exactly *((E1)+(E2)). The array name becomes a pointer to the first element, and adding an integer moves forward by that many elements. So a[2] means "the element two positions after the first". The index is an offset from the start, and the first element is zero positions from the start. That is why this compiles and gives the same element:

int a[3] = {1, 2, 3};
printf("%d %d\n", a[2], 2[a]);   /* both print 3 */

You should never write 2[a], but it shows that indexing is addition. Other languages do not all expose pointers, but the idea of "how far from the start" carries over.

The range reason

Edsger Dijkstra's note EWD831 argues for numbering from zero using ranges. He prefers the convention a <= i < b: include the lower bound, exclude the upper bound. For a sequence of length N, starting at 1 gives the awkward range 1 <= i < N+1, while starting at 0 gives 0 <= i < N. With zero-based numbering, an element's index also equals the number of elements before it.

You can see the same convention in Python slices. The documentation defines s[i:j] as the items with index k such that i <= k < j. The length of a slice is then simply j - i, and two neighboring slices s[0:3] and s[3:6] never overlap or leave a gap.

This is a design argument, not a law of nature. A language could choose another starting point. What matters in practice is knowing which rule the language you are using follows.

The last element and the length

Because the first index is 0, the count and the last index differ by one. A five-element array has length 5 and last index 4. This is the source of most indexing mistakes:

Array of 5 elementsValue
First index0
Last valid index4 (length minus 1)
Loop conditioni < 5
First invalid index5 (equal to the length)

A loop written as for (int i = 0; i <= 5; i++) runs six times and reads index 5, one past the end. Use < against the length, not <=. This kind of bug is called an off-by-one error.

Negative indexes

Some languages let you count from the end. Python does it with square brackets. The documentation says that if the index is negative, it is relative to the end of the sequence: len(s) + i is substituted. The documentation also notes that -0 is still 0.

s = "spam"      # len(s) == 4
s[0]            # 's'
s[-1]           # 'm'  (len(s) + -1 = 3)
s[1:-1]         # 'pa' (the end index becomes 3)

These results follow from the rules in the documentation. JavaScript square brackets do not work this way, but the array method at() "accepts negative integers, which count back from the last item". So fruits.at(-1) returns the last element, the same as fruits[fruits.length - 1]. In C, a negative index on an array has no defined meaning: pointer arithmetic is defined only while the result stays inside the array or one past its end, so something like a[-1] is undefined behavior.

What happens when the index is out of range

The result differs by language, and the difference matters when you debug:

LanguageReading past the end
PythonRaises IndexError if the index is outside the sequence range
JavaScriptReturns undefined (MDN: an index larger than the array's length returns undefined)
CNo check. Undefined behavior: it may crash, return garbage or appear to work

Python's slices are different from single indexes. Out-of-range slice bounds are clamped instead of raising an error, so "spam"[2:100] gives 'am' and a slice whose start is not below its end gives an empty sequence.

JavaScript has one more quirk. Writing past the end does not fail: assigning to an index beyond the current bounds extends the array and updates length, leaving empty slots in between. MDN shows that after fruits[5] = "mango" on a two-element array, fruits.length is 6, and fruits[8] is still undefined.

The quiet failure in JavaScript and the undefined behavior in C are harder to notice than Python's exception. If a value comes back as undefined or as garbage, check whether your index equals the length.

Common indexing mistakes

  • Using the length as an index. a[n] on an n-element array is one past the end. The last element is a[n - 1].
  • Counting from 1 in your head. "The third item" is index 2. When you translate a human position into an index, subtract 1.
  • Looping with <=. Compare against the length with <.
  • Taking the last element of an empty array. a[len - 1] with a length of 0 asks for index -1. In Python, s[-1] on an empty list is outside the sequence range, so it raises IndexError; in C it is undefined behavior. Check for an empty array first.
  • Assuming other languages match. Before using negative indexes or relying on a returned value for a bad index, read the language's documentation.

Where to go next

For the C details, including why sizeof stops working inside a function, see Arrays in C: declare, index and pass to functions. For the Python side, Array in Python: lists vs the array module vs NumPy arrays covers which type people mean when they say "array" in Python.

Frequently asked questions

Do all programming languages start array indexes at 0?
No, but C, Python and JavaScript do, and so do most languages derived from or influenced by them. The three languages covered here define the first element as index 0. Check the documentation of any language you are new to, because the starting index is part of the language definition, not something you can change in your own code.
What is the last valid index of an array?
For an array with n elements, the last valid index is n - 1. In JavaScript that is array[array.length - 1], in Python it is s[len(s) - 1] or simply s[-1], and in C you track the length yourself and use a[n - 1].
What is an off-by-one error?
An off-by-one error is a loop or index that is exactly one too high or too low, such as looping while i <= n instead of i < n. With zero-based indexes, the first form reaches index n, which is one past the end of an n-element array.
What does a negative array index mean?
It depends on the language. In Python, a negative index counts from the end, so s[-1] is the last item. In JavaScript, square brackets do not do this, but the at() method does. In C, a negative index is not defined for an array and is undefined behavior.

Sources