🔢 Index
5th Grade 💻 Coding
An index is the position number of an item in a list or a character in a string. In most programming languages, counting starts at 0, so the first item is at index 0.
In the list colors = ["red", "green", "blue"], colors[0] is “red,” colors[1] is “green” and colors[2] is “blue.” The last item in a list of 3 is at index 2. Python also has a shortcut: colors[-1] is always the last item.
If you ask for an index that doesn’t exist, like colors[5], you get an error called IndexError. It’s one of the most common mistakes, so programmers check the list’s length with len. Strings have indexes too: "hello"[0] is the letter h.
For example
- In a line at the doctor’s office, whoever is at index 0 goes in first.
- In some countries, the ground floor of a building is called “floor 0,” just like an index.
- With
colors = ["red", "green", "blue"], the expressioncolors[-1]gives “blue,” the last item.
📌 Remember: Indexes start at 0. The last one = the length minus 1.
Quick quiz
What is the index of the first item in a Python list?
In a list of 3 items, what is the index of the last one?
What happens when you ask for an index that doesn’t exist?