EMZETT.
Login

Index

In short: The position number of an element within an ordered data structure like an array or a list — in most languages, counting starts at 0, not 1.

In more detail: An index allows direct access to a specific element, with no need to search through the structure in order (array[3], for example, immediately accesses the fourth element). This zero-based counting is a common source of error for beginners (“off-by-one errors”), for instance when a loop runs up to array.length instead of array.length - 1 and thereby accesses an index outside the valid bounds.

In Depth

Why do most languages start at 0 instead of 1? Technically, the index of an array historically describes the memory offset from the start of the array — the first element sits right at the start, so offset 0. This convention (shaped, among others, by C) has become established in most modern languages (Java, Python, JavaScript, C++), even though modern arrays are often no longer laid out that simply in memory internally. A few languages (e.g. Lua, MATLAB) deliberately count from 1.

numbers = [10, 20, 30, 40]
numbers[0]   # 10 - first element
numbers[3]   # 40 - fourth (last) element
numbers[4]   # error! index outside the valid range (0-3)
numbers[-1]  # 40 - Python special case: negative index counts from the end

The classic off-by-one error usually arises in loop conditions:

// WRONG - runs one step too far (index == length doesn't exist)
for i from 0 to LENGTH(array):
    process(array[i])
 
// CORRECT - the loop ends BEFORE i reaches the length
for i from 0 to LENGTH(array) - 1:
    process(array[i])

For an array with 4 elements, the valid indices are 0, 1, 2, 3 — index 4 (i.e. array[LENGTH(array)]) doesn’t exist. This error is so widespread because the boundary (< length vs. <= length) differs by only a single character and is easily mixed up mentally, but in the worst case leads to a program crash or — in languages with no automatic bounds checking like C — to unpredictable behaviour (accessing foreign memory).

Most modern languages and libraries therefore offer ways to avoid manually managing the index at all — such as a “for-each” loop that iterates directly over the elements instead of over indices, when the index itself isn’t needed.

See also: Arrays, For Loop, List