Skip to content
BENIBIX Learn

Index

Development🧩 Programming ConceptsData and Variables

Also known as Array Index, Position

The number of a spot in a list. In most languages the first spot is 0.

Think of it like

Think of it like a seat number at the cinema. It tells you which seat is yours.

Example

Jack asks for fruits[3] in a list of three fruits. Python stops with an IndexError, because the spots are 0, 1 and 2.

Why it matters

Every time code picks one item out of many, it uses an index. Getting it one off is a very common bug.

Definition

An index is the number of a spot in an array or a string. Most languages start counting at 0, so the first item has index 0. You use the index in square brackets to read or change one item, like fruits[2]. Asking for an index past the end gives an error. Some languages also count back from the end with -1.

Example code

python
>>> fruits = ["apple", "pear", "plum"]
>>> fruits[2]
'plum'
>>> fruits[3]
IndexError: list index out of range
Spot 2 is the last fruit. Spot 3 does not exist, so Python stops.

Common mistake

Being off by one: starting at 1, or going one step past the end of the list.

Key takeaways

  1. 1
    A spot number. It says where an item sits.
  2. 2
    Zero first. The first item is at index 0.
  3. 3
    Stay in range. Past the end is an error.

Learn it properly