Sub topic 2
Reading items by index
This chapter assumes you can create a list with square brackets, use variables, and write a basic for loop. It covers reading single items. Reading ranges of items is the topic of the next chapter.
How positions are numbered
A list keeps its items in order. Each item has a position called an index, which is an integer. Counting starts at 0, so the first item has index 0.
Python also numbers items from the end. The last item has index -1, the one before it has index -2, and so on.
| Item | Index | Negative index |
|---|---|---|
| "apple" | 0 | -4 |
| "banana" | 1 | -3 |
| "cherry" | 2 | -2 |
| "date" | 3 | -1 |
Reading with square brackets
Write the list, then the index in square brackets.
fruits = ["apple", "banana", "cherry", "date"]
print(fruits[0]) # apple
print(fruits[3]) # date
print(fruits[-1]) # date
print(fruits[-2]) # cherryA negative index -n means len(fruits) - n. Use -1 to get the last item. It is shorter than fruits[len(fruits) - 1] and harder to get wrong.
Reading by index does not change the list. It returns the item that is stored at that position.
The valid range
For a list of length n, the valid indices run from -n to n - 1. Any other integer raises an IndexError.
fruits = ["apple", "banana", "cherry", "date"]
try:
print(fruits[4])
except IndexError as error:
print(error) # list index out of rangeThe most common cause is an off-by-one mistake. A list of length 4 has no index 4, so fruits[len(fruits)] always fails. An empty list has no valid index at all, which means [][-1] also raises IndexError. When a list might be empty, check it first.
fruits = []
if fruits:
print(fruits[-1])
else:
print("no fruits")The index must be an integer. A float such as fruits[1.0] or a string such as fruits["1"] raises TypeError, not IndexError.
Using a computed index
The index can be any expression that produces an integer.
fruits = ["apple", "banana", "cherry", "date"]
middle = len(fruits) // 2
print(fruits[middle]) # cherryHere // is integer division, so 4 // 2 gives 2 and not 2.0.
Writing with an index
The same syntax on the left side of an assignment replaces the item at that position.
fruits = ["apple", "banana", "cherry", "date"]
fruits[0] = "avocado"
print(fruits) # ['avocado', 'banana', 'cherry', 'date']The index must already exist. You cannot grow a list by assigning to a position past the end. Use append for that, which a later chapter covers.
Quick reference
items[0]is the first item.items[-1]is the last item.- Valid indices run from
-len(items)tolen(items) - 1. - An out-of-range index raises
IndexError. - A non-integer index raises
TypeError.
Exercise
Given colors = ["red", "green", "blue"], what do colors[-3] and colors[3] do?
Show answer
colors[-3] returns "red", because -3 is the first position counting from the end. colors[3] raises IndexError, because the valid indices for a list of length 3 run from -3 to 2.
Exercise
Write a line that safely prints the last item of a list named names, and prints "empty" if the list has no items.
Show answer
print(names[-1] if names else "empty"). An empty list is falsy, so the condition avoids the IndexError that names[-1] would raise.