List Indexes

The important thing about lists is that they are what's known as ordered. That means that every item in a list will stay in its place, and they won't swap themselves around when you're not looking. That might seem obvious, but as you'll see in the next couple of pages, not everything in Python behaves like that.

Just like strings and variables, each item in a list can be described with an index. As we mentioned earlier, an index is that item's position in the list (look back here or here if you need to remember how these work).

>>> fruit = ["apple", "banana", "grape"]

The list fruit has three items in it. So if we were going to describe the position of each item, we might say that "apple" is the first item, "banana" is the second, and "grape" is third.

But remember: Python always starts counting at zero!

['apple', 'banana', 'grape']

0 1 2

So in the fruit list, "apple" is actually at index 0, "banana" is at index 1, and "grape" is at index 2. We still have three items in the list, we're just counting them and describing their positions in a way that you might not expect.

What if we have a list and we want to find out what the first item is?

>>> fruit[0]

Here we typed the variable name of the list, and then right next to it the number of the index we're looking for. The number should be inside square brackets, and there should not be a space between the brackets and the word fruit.

>>> fruit[0]

'apple'

How would we find out what the second item is? What about the item at the index 2? Are they the same thing?

>>> fruit[1]

'banana'

>>> fruit[2]

'grape'

What happens if we try to get an item from the list at the index 3?

>>> fruit[3]

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

IndexError: list index out of range

Do you know why we got that error message?

We have only three items in the list. If Python starts counting at 0, then the only indexes (or indices) we have would be 0, 1, and 2.

So there is no index 3 in our fruit list. Python lets you know that with an IndexError.