Lessons · Python · the first item is item 0
Counting from zero
The first item is at position 0, not 1.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
Every list, every row of results, every character of text is reached by position. Off by one here is the single most common bug in all of programming, and it starts with this.
How to think about it
Ask: how many steps from the START is this? The first item is zero steps in, so it is index 0. The last is one less than the length.
Worked example
items = ["a", "b", "c"]Three items, at positions 0, 1 and 2.
print(items[0])Zero steps from the start, so this prints a.
print(items[-1])Negative counts back from the end, so this prints c without you needing to know the length.
Your turn
Print the SECOND item.
items = ["a", "b", "c"] print(items[])
Solve one with the tests running
The trap
items[3] on a three item list raises IndexError, because the last valid position is 2. len(items) is never a valid index.
Practise the first item is item 0 on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.