Programming Search⌘K

Conceptintro

Array indexing

Also called array index, subscript, index origin, zero-based indexing, one-based indexing, negative index, bounds check, index out of range.

Array indexing selects an item of an array by its position. Most languages count from 0, some count from 1, and many check that the index is inside the array.

Applies to
core-languages

Idea

An array keeps its items in order, and an index is the number of an item's position. a[i] reads the item at index i. The language decides three things about indices:

  • the origin, which is the index of the first item: 0 in most languages, 1 in some;
  • what a negative index means: an error, or a position counted from the end;
  • what happens when the index is out of bounds: an exception, a special value, or undefined behavior.

Wikipedia defines the most common origin: "Zero-based numbering is a way of numbering in which the initial element of a sequence is assigned the index 0, rather than the index 1 as is typical in everyday non-mathematical or non-programming circumstances"1. With origin 0, an array of length n has the indices 0 to n - 1.

a = ["a", "b", "c", "d"]

# The first item has index 0 and the last has index len(a) - 1.
print(a[0], a[3], a[len(a) - 1], len(a))

# Item i starts i * size bytes after the start of the array.
base, size = 1000, 4
print([base + size * i for i in range(len(a))])

# With indices from 1, the same address needs an extra subtraction.
print([base + size * (i - 1) for i in range(1, len(a) + 1)])

# An index outside 0 to len(a) - 1 is an error.
try:
    a[4]
except IndexError as e:
    print("IndexError:", e)
Output
a d d 4
[1000, 1004, 1008, 1012]
[1000, 1004, 1008, 1012]
IndexError: list index out of range

The two address lists are the same, but the second formula has one more subtraction. Index 4 is past the end of a list of length 4, so Python raises IndexError.

How it works

An index is an offset. The items of an array are next to each other in memory, so the address of an item is the start of the array plus the index times the size of an item. Wikipedia gives the two formulas: with indices from 1, "the desired address is computed by this expression: a+s×(i−1), where s is the size of each element. In contrast, if the index numbers count from 0, the expression becomes a+s×i. This simpler expression is more efficient to compute at run time"1. C defines indexing as this arithmetic: "By definition, the subscript operator E1[E2] is exactly identical to *((E1)+(E2))"2. So in C, a[2], *(a + 2) and even 2[a] are the same item. In the C example, &a[3] - &a[0] is 3 items and 12 bytes.

Why 0. Dijkstra argued from ranges. With the half-open convention start ≤ i < end, indices from 1 give the range 1 ≤ i < N+1, but "starting with 0, however, gives the nicer range 0 ≤ i < N". He concluded that "an element's ordinal (subscript) equals the number of elements preceding it in the sequence"3. The index of an item is how many items come before it. See range.

Why 1. Indices from 1 match the way people count and the notation of mathematics. Wikipedia says that one-based arrays are "the traditional convention in mathematics for matrices and mathematical sequences"4, and that "Fortran or COBOL, have array subscripts starting with one, because they were meant as high-level programming languages"1. Lua tables can use any index, but "it is customary in Lua to start arrays with index 1. The Lua libraries adhere to this convention"5. Some languages let the program choose: "A few languages, such as Pascal and Lua, support n-based array types, whose minimum legal indices are chosen by the programmer"4.

Negative indices. Some languages read a negative index from the end. In Python, "If i or j is negative, the index is relative to the end of sequence s: len(s) + i or len(s) + j is substituted. But note that -0 is still 0"6. So a[-1] is the last item. JavaScript brackets do not do this, but the at method does: "Negative integers count back from the last item in the array"7. C# has a separate operator: "For any number n, the index ^n is the same as sequence.Length - n"8, so the index ^1 is the last item and ^0 is one past the end. Java, Go, Rust, C and C++ have no negative indices.

Bounds checks. A bounds check tests that 0 ≤ i < length before the access. Wikipedia describes it as a test "that a variable being used as an array index is within the bounds of the array (index checking). A failed bounds check usually results in the generation of some sort of exception signal"9. Java checks every access: "All array accesses are checked at run time; an attempt to use an index that is less than zero or greater than or equal to the length of the array causes an ArrayIndexOutOfBoundsException to be thrown"10. In Go, "the index x is in range if 0 <= x < len(a), otherwise it is out of range", and "if x is out of range at run time, a run-time panic occurs"11. In Rust, "If the index is greater than or equal to the length, Rust will panic"12. C does not check, and an access out of bounds is undefined behavior. See out-of-bounds read and out-of-bounds write.

In languages

LanguageVerdictNote
PythonNative
C++Native
JavaNative
CNative
C#Native
JavaScriptNative
TypeScriptNativeTypeScript uses the JavaScript rules. With the noUncheckedIndexedAccess option, the type of a[i] includes undefined, so the compiler asks the code to handle a missing item. No example file exists.
GoNative
RustNative
KotlinNativeIndices start at 0, and lastIndex is size - 1. A bad index throws IndexOutOfBoundsException, and getOrNull and getOrElse return a value instead. No example file exists because kotlinc is not installed.
SQLNativePostgreSQL arrays start at 1 by default, and an index out of bounds gives NULL. ROW_NUMBER() numbers rows from 1.
BashNativeIndexed arrays start at 0, and ${a[-1]} is the last item. An unset index gives an empty string and no error. No example file exists.
PowerShellNativeArrays start at 0, and $a[-1] is the last item. An index out of bounds gives $null and no error unless strict mode is on. No example file exists because pwsh is not installed.
HTMLDoes not applyHTML is markup and has no array indices.
CSSDoes not applyCSS has no arrays. The nth-child selector counts elements from 1.
Regular expressionsDoes not applyA regular expression has no array indices. Capture groups are numbered from 1, and group 0 is the whole match.
Language Verdict Mechanism
Python native origin 0; negative indices count from the end; IndexError out of bounds; slices cut their bounds
JavaScript native origin 0; at(-1) counts from the end; an index out of bounds gives undefined
TypeScript native the JavaScript rules; noUncheckedIndexedAccess adds undefined to the type of a[i]
Java native origin 0, int indices; ArrayIndexOutOfBoundsException; List.get throws IndexOutOfBoundsException
Kotlin native origin 0; getOrNull and getOrElse; lastIndex; an exception out of bounds
C# native origin 0; ^n counts from the end; IndexOutOfRangeException on arrays
Go native origin 0; a run-time panic out of bounds; a constant index out of range is a compile error
Rust native origin 0, usize indices; a panic out of bounds; get returns an Option
C native origin 0; a[i] is *(a + i); no bounds check, and an access out of bounds is undefined behavior
C++ native origin 0; operator[] does not check; at() throws std::out_of_range
Bash native origin 0 for indexed arrays; a negative index counts from the end; an unset index gives an empty string
PowerShell native origin 0; $a[-1] is the last item; an index out of bounds gives $null
SQL native PostgreSQL arrays start at 1 by default and give NULL out of bounds; ROW_NUMBER() numbers rows from 1
Regex n/a a pattern has no array indices; capture groups are numbered from 1, and group 0 is the whole match
HTML n/a markup; :nth-child(1) in CSS selects the first child, so selectors count from 1
CSS n/a style rules have no arrays; nth-child counts from 1

The languages give four answers to an index out of bounds. Java, C#, Python and C++ at() throw an exception. Go and Rust stop the program with a panic. JavaScript, PowerShell and PostgreSQL return a special value such as undefined or NULL. C and C++ operator[] do not check, so the behavior is undefined.

The example files show these rules. Python uses negative indices, IndexError on both sides, slices that cut their bounds, enumerate from 1 and i % n to wrap an index. JavaScript shows at(-1), a[-1] as a property lookup, undefined past the end, a sparse array and a typed array that ignores a write out of bounds. Java shows the exception messages for arrays, a List and Objects.checkIndex. C# shows ^n, the Index type, ^0 and the two exception types. Go recovers from the panics and shows that a string index is a byte. Rust uses get, first, last, try_from for a negative value, checked_sub and byte indices into a string. C shows that a[i], *(a + i) and i[a] are the same and writes its own bounds check. C++ compares operator[] with at(), counts down with std::ssize, and uses std::get on a std::array.

PythonGitHub
import array

a = ["a", "b", "c", "d", "e"]
# A negative index counts from the end: a[-i] is a[len(a) - i].
print(a[-1], a[-2], a[len(a) - 2], a[-0])

# An index past either end raises IndexError, but a slice cuts its bounds.
for i in (5, -6):
    try:
        a[i]
    except IndexError as e:
        print(i, "IndexError:", e)
print(a[3:99], a[-99:2])

# An index must be an integer.
try:
    a[1.0]
except TypeError as e:
    print("TypeError:", e)

# enumerate gives indices from 0, or from any start, such as 1 for people.
print(list(enumerate("xyz")), list(enumerate("xyz", start=1)))

# i % n wraps an index into 0 to n - 1, as in a ring buffer.
print([a[i % len(a)] for i in range(3, 8)])

# An array from the array module stores machine numbers one after another.
nums = array.array("i", [10, 20, 30])
print(nums.itemsize, nums[2], nums.buffer_info()[1])
Output
e d d a
5 IndexError: list index out of range
-6 IndexError: list index out of range
['d', 'e'] ['a', 'b']
TypeError: list indices must be integers or slices, not float
[(0, 'x'), (1, 'y'), (2, 'z')] [(1, 'x'), (2, 'y'), (3, 'z')]
['d', 'e', 'a', 'b', 'c']
4 30 3
  • Verdict: native. A negative index counts from the end, and a[-0] is a[0]. An index past either end raises IndexError, but a slice cuts its bounds. A float index raises TypeError. enumerate gives indices from 0 or from 1, and i % n wraps an index. An array from the array module stores machine integers of 4 bytes each.
#include <array>
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>

int main() {
    std::vector<int> v{10, 20, 30};
    // operator[] does not check the index. at() checks it and throws std::out_of_range.
    std::cout << v[0] << ' ' << v.at(2) << ' ' << v.back() << '\n';
    try {
        std::cout << v.at(3) << '\n';
    } catch (const std::out_of_range& e) {
        std::cout << "out_of_range\n";
    }

    // size() is unsigned. ssize gives a signed size, so a loop that counts down can test i >= 0.
    for (auto i = std::ssize(v) - 1; i >= 0; --i) std::cout << v[i] << ' ';
    std::cout << '\n';

    // std::array has a size known at compile time, and std::get checks the index at compile time.
    std::array<int, 3> a{1, 2, 3};
    std::cout << std::get<2>(a) << ' ' << a.size() << '\n';

    // A string index gives a char, which is one byte.
    std::string s = "héllo";
    std::cout << s.size() << ' ' << s[0] << '\n';
}
Output
10 30 30
out_of_range
30 20 10
3 3
6 h
  • Verdict: native. operator[] does not check the index, and at() throws std::out_of_range. std::ssize gives a signed size, so a count down can test i >= 0. std::get on a std::array checks the index at compile time. A string index gives one byte.
JavaGitHub
import java.util.List;
import java.util.Objects;

public class Main {
    public static void main(String[] args) {
        int[] a = {10, 20, 30, 40, 50};
        // Indices go from 0 to length - 1.
        System.out.println(a[0] + " " + a[a.length - 1] + " " + a.length);

        // Every array access is checked. A bad index throws ArrayIndexOutOfBoundsException.
        for (int i : new int[] {5, -1}) {
            try {
                System.out.println(a[i]);
            } catch (ArrayIndexOutOfBoundsException e) {
                System.out.println(e.getMessage());
            }
        }

        // A List throws IndexOutOfBoundsException. Java has no negative indices.
        List<String> list = List.of("x", "y", "z");
        System.out.println(list.get(list.size() - 1) + " " + list.getLast());
        try {
            list.get(3);
        } catch (IndexOutOfBoundsException e) {
            System.out.println(e.getClass().getSimpleName() + ": " + e.getMessage());
        }

        // Objects.checkIndex does the same check for code that keeps its own storage.
        System.out.println(Objects.checkIndex(2, 3));
        try {
            Objects.checkIndex(3, 3);
        } catch (IndexOutOfBoundsException e) {
            System.out.println(e.getMessage());
        }

        // A char index is promoted to int.
        char c = 2;
        System.out.println(a[c]);
    }
}
Output
10 50 5
Index 5 out of bounds for length 5
Index -1 out of bounds for length 5
z z
ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
2
Index 3 out of bounds for length 3
30
  • Verdict: native. Every array access is checked, and a bad index on either side throws ArrayIndexOutOfBoundsException with the index and the length. The list from List.of throws a subclass of IndexOutOfBoundsException for index 3. Java has no negative indices, but getLast gives the last item. Objects.checkIndex does the same check for other code. A char index is promoted to int.
#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>

// C does not check indices. A checked access is the program's own code.
static bool get(const int *a, size_t n, size_t i, int *out) {
    if (i >= n) return false;
    *out = a[i];
    return true;
}

int main(void) {
    int a[] = {10, 20, 30, 40, 50};
    size_t n = sizeof a / sizeof a[0];

    // a[i] is defined as *(a + i), so i[a] is the same item.
    printf("%d %d %d %d\n", a[2], *(a + 2), 2[a], a[n - 1]);

    // Item i is i * sizeof(int) bytes after the start of the array.
    printf("%td %td %zu\n", &a[3] - &a[0], (char *)&a[3] - (char *)&a[0], sizeof a[0]);

    int v = 0;
    bool ok = get(a, n, 4, &v);
    printf("%d %d ", ok, v);
    ok = get(a, n, 5, &v);
    printf("%d\n", ok);

    // A pointer one past the last item is valid for comparison, but not for reading.
    int sum = 0;
    for (const int *p = a; p != a + n; p++) sum += *p;
    printf("%d\n", sum);
    return 0;
}
Output
30 30 30 50
3 12 4
1 50 0
150
  • Verdict: native. a[i] is *(a + i), so 2[a] is the same item. Item 3 is 3 items and 12 bytes after item 0 when an int has 4 bytes. C does not check indices, so the program writes its own get with a bounds test. A pointer one past the end ends the loop.
using System;
using System.Collections.Generic;

class Program
{
    static void Main()
    {
        int[] a = { 10, 20, 30, 40, 50 };
        // Indices go from 0 to Length - 1, and ^n counts from the end.
        Console.WriteLine($"{a[0]} {a[a.Length - 1]} {a[^1]} {a[^2]}");

        // An Index is a value. GetOffset turns ^2 into a position for a given length.
        Index i = ^2;
        Console.WriteLine($"{i} {i.GetOffset(a.Length)} {i.IsFromEnd}");

        // A bad index on an array throws IndexOutOfRangeException. ^0 is one past the end.
        foreach (var bad in new[] { 5, -1 })
        {
            try { Console.WriteLine(a[bad]); }
            catch (IndexOutOfRangeException e) { Console.WriteLine(e.GetType().Name); }
        }
        try { Console.WriteLine(a[^0]); }
        catch (IndexOutOfRangeException) { Console.WriteLine("^0 is out of range"); }

        // A List<T> throws ArgumentOutOfRangeException instead.
        var list = new List<string> { "x", "y", "z" };
        try { Console.WriteLine(list[3]); }
        catch (ArgumentOutOfRangeException e) { Console.WriteLine($"{e.GetType().Name} {list[^1]}"); }
    }
}
Output
10 50 50 40
^2 3 True
IndexOutOfRangeException
IndexOutOfRangeException
^0 is out of range
ArgumentOutOfRangeException z
  • Verdict: native. ^n counts from the end, and an Index is a value that GetOffset turns into a position. An array throws IndexOutOfRangeException for 5, for -1 and for ^0, which is one past the end. A List throws ArgumentOutOfRangeException instead.
JavaScriptGitHub
const a = ["a", "b", "c", "d", "e"];

// Indices start at 0. at() accepts a negative index and counts from the end.
console.log(a[0], a[a.length - 1], a.at(-1), a.at(-2));

// Brackets do not count from the end: a[-1] looks up a property named "-1".
console.log(a[-1], a.at(-6));

// An index past the end gives undefined. It does not throw.
console.log(a[5], a[99]);

// An index is converted to a string property key, so a["2"] is a[2].
console.log(a["2"], Object.keys(a).slice(0, 3));

// A write far past the end makes a sparse array with holes.
const b = [1, 2];
b[5] = 6;
console.log(b.length, b, 3 in b);

// A typed array ignores a write out of bounds.
const t = new Int32Array(3);
t[3] = 7;
console.log(t.length, t[3], t);
Output
a e e d
undefined undefined
undefined undefined
c [ '0', '1', '2' ]
6 [ 1, 2, <3 empty items>, 6 ] false
3 undefined Int32Array(3) [ 0, 0, 0 ]
  • Verdict: native. Indices start at 0, and at() counts from the end with a negative index. a[-1] looks up a property named "-1" and gives undefined. An index past the end gives undefined and does not throw. Index keys are strings. A write far past the end makes a sparse array, and a typed array ignores a write out of bounds.
package main

import "fmt"

func at(a []int, i int) (v int, err error) {
	defer func() {
		if r := recover(); r != nil {
			err = fmt.Errorf("%v", r)
		}
	}()
	return a[i], nil
}

func main() {
	a := []int{10, 20, 30, 40, 50}
	// Indices go from 0 to len(a)-1. Go has no negative indices.
	fmt.Println(a[0], a[len(a)-1], len(a))

	// An index out of range at run time panics. recover turns the panic into an error here.
	for _, i := range []int{4, 5, -1} {
		v, err := at(a, i)
		fmt.Println(i, v, err)
	}

	// A constant index that is out of range is a compile-time error, so the compiler
	// rejects a[-1] and a[5] on an array of length 5.
	arr := [5]int{1, 2, 3, 4, 5}
	i := 4
	fmt.Println(arr[i], len(arr))

	// A string index gives a byte, not a character.
	s := "héllo"
	fmt.Println(len(s), s[1], s[2], string([]rune(s)[1]))
}
Output
10 50 5
4 50 <nil>
5 0 runtime error: index out of range [5] with length 5
-1 0 runtime error: index out of range [-1]
5 5
6 195 169 é
  • Verdict: native. Indices go from 0 to len(a)-1, and Go has no negative indices. An index out of range at run time panics with the index and the length, and recover turns the panic into an error. A constant index out of range is a compile-time error. A string index gives a byte, so "héllo" has 6 bytes.
RustGitHub
fn main() {
    let a = [10, 20, 30, 40, 50];
    // Indices are usize and go from 0 to len - 1.
    println!("{} {} {}", a[0], a[a.len() - 1], a.len());

    // get returns None for an index out of bounds. a[i] would panic.
    println!("{:?} {:?} {:?} {:?}", a.get(4), a.get(5), a.first(), a.last());

    // An index cannot be negative. A signed value must be converted, and the conversion can fail.
    let i: i64 = -1;
    println!("{:?} {:?}", usize::try_from(i), usize::try_from(3i64).map(|k| a[k]));

    // checked_sub avoids an underflow when the code computes the last index of an empty slice.
    let empty: [i32; 0] = [];
    println!("{:?} {:?}", empty.len().checked_sub(1), a.len().checked_sub(1));

    // Count from the end with len - k, or with iter().rev().
    let k = 2;
    println!("{} {:?}", a[a.len() - k], a.iter().rev().nth(k - 1));

    // A str index is a byte range, and it must end on a character boundary.
    let s = "héllo";
    println!("{} {:?} {:?}", s.len(), s.get(0..2), s.get(0..3));
}
Output
10 50 5
Some(50) None Some(10) Some(50)
Err(TryFromIntError(NegOverflow)) Ok(40)
None Some(4)
40 Some(40)
6 None Some("hé")
  • Verdict: native. Indices are usize, and get returns None out of bounds where a[i] would panic. A negative i64 does not convert to usize. checked_sub gives None for the last index of an empty slice. Count from the end with len - k or rev. A str index is a byte range, and get returns None when the range ends inside a character.
  • Arbitrary lower bounds. Wikipedia notes that "Ada, ALGOL 60, PL/I, allow an arbitrary lower bound for each index"1, and Pascal allows any ordinal type as the index type1, so an array can be indexed by the days of the week.
  • A run-time origin. "APL allows setting the index origin to 0 or 1 during runtime programmatically"1.
  • Index types. Rust uses the unsigned usize, so a negative index cannot exist, and a signed value must be converted first. Java uses int, so the length of an array must fit in an int.
  • Multidimensional indices. m[i][j] selects a row and then an item. A true matrix computes one offset from both indices. See multidimensional array.
  • Strings. A string index can count bytes, code units or characters, and each choice gives a different item for a non-ASCII string. In the Go and Rust examples, "héllo" has 6 bytes. See string indexing.
  • Safe access. get in Rust, getOrNull in Kotlin and at in JavaScript return a value that marks a missing item instead of an error.

Pitfalls

  • Off by one. The last index is length - 1, not length. A loop with i <= n reads one item too far. Wikipedia notes that zero-based indexing "can avoid off-by-one or fencepost errors"4 when the code uses half-open ranges, but a mix of 0-based and 1-based code causes them.
  • Mixed origins. Data from people, SQL and Lua is often 1-based, and the program is 0-based. Convert at the edge of the program, in one place.
  • Negative indices by mistake. In Python, an index computed as i - 1 is -1 when i is 0, and it reads the last item without an error. In JavaScript, a[-1] gives undefined, not the last item.
  • Silent results. JavaScript returns undefined and does not throw, so a wrong index can travel far before it causes an error. A write far past the end of a JavaScript array makes a sparse array with holes.
  • Unsigned arithmetic. In C, C++ and Rust, len - 1 on an empty array wraps around to the largest value, or panics in a Rust debug build. Test for an empty array first, or use checked_sub or a signed size.
  • No check in C. An index out of bounds in C or with C++ operator[] reads or writes other memory. The program can continue with wrong data, and an attacker can use it. Use a checked access when the index comes from input.

Cost

Operation Time Notes
read or write a[i] constant one multiply and one add for the address
bounds check constant one compare and a branch, often removed by the compiler
negative index constant one more add of the length
index into a linked list linear in i the list must follow i links

Indexing is constant time only for contiguous storage. The cost of a bounds check is small, and compilers remove it when they can prove the index is in range, for example in a loop from 0 to the length. Wikipedia calls this "Bounds-checking elimination"9.

History

Early high-level languages used origin 1. FORTRAN counted from 1, and ALGOL 60 and Pascal let the program give both bounds. Dijkstra wrote that "In FORTRAN subscripts always start at 1; in ALGOL 60 and in PASCAL, convention c) has been adopted"3, where convention c) includes both bounds. Index checking also came early: Wikipedia lists ALGOL 60, ALGOL 68 and Pascal among the "Early compiled programming languages with index checking ability"9. In his 1980 Turing Award lecture, C. A. R. Hoare said of ALGOL 60 that "every occurrence of every subscript of every subscripted variable was on every occasion checked at run time against both the upper and the lower declared bounds of the array"9.

Origin 0 came from systems languages. Martin Richards, the creator of BCPL, "designed arrays initiating at 0 as the natural position to start accessing the array contents in the language, since the value of a pointer p used as an address accesses the position p + 0 in memory"1. BCPL was a precursor of C1, and C kept arrays that start at 0. In 1982, Dijkstra gave the argument from half-open ranges in EWD 8313. Newer languages kept origin 0 and added safer access: C# has ^n, JavaScript has at, and Rust and Go check every index.

References

  1. Zero-based numbering, Wikipedia, Introduction; Origin; Usage in programming languages
  2. Member access operators, C, cppreference.com, Subscript
  3. Edsger W. Dijkstra, Why numbering should start at zero (EWD 831), 1982, Full text
  4. Array (data type), Wikipedia, Index origin
  5. Arrays, Programming in Lua (first edition), Section 11.1
  6. Built-in Types, The Python Standard Library, Common Sequence Operations, notes 3 and 4
  7. Array.prototype.at(), MDN Web Docs, Description
  8. Indices and ranges, C# documentation, Language support for indices and ranges
  9. Bounds checking, Wikipedia, Introduction; Index checking
  10. Chapter 10, Arrays, The Java Language Specification, Java SE 25, 10.4 Array Access
  11. The Go Programming Language Specification, Index expressions
  12. Data Types, The Rust Programming Language, Invalid Array Element Access

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/RAT491/text.yaml