Menu

Arrays (Lists)

List Indexes and Length

A list stores many values under one name, and each value sits at a position called its index. Indexes start at 0, so the first item is at index 0 and the second at index 1.

Reading, replacing and displaying items

Write the list name followed by an index in square brackets. Reading an item copies its value out so you can use it, replacing an item assigns a new value to that position, and displaying an item prints it. In a list of five scores, scores[0] gives you the first score and scores[2] = 21 overwrites the third. Every other item stays as it was, which is far easier than managing five separate variables.

scores = [12, 7, 19, 4, 15]
print(scores[0])          # read the first item
scores[2] = 21            # replace the third item
print(scores[2])
print(len(scores))
total = 0
for i in range(len(scores)):
    total = total + scores[i]
print("Total: " + str(total))

Output:

12
21
5
Total: 59

Length and the valid range of indexes

The length of a list is the number of items it contains, and len() returns that number. Length is not the last index: a list of five items has valid indexes 0 to 4, so the last index is always len(scores) - 1. Length does two useful jobs. It controls a loop, because range(len(scores)) visits every index once and still works when items are added or removed. It also works out the final position, so you avoid an out-of-range index.

A list called scores holding 12, 7, 19, 4 and 15 at indexes 0 to 4. len(scores) is 5, the last index is len(scores) - 1 = 4, and scores[5] is out of range and causes an IndexError.

An index past the end causes an error and the program stops, because nothing is stored there: a list of five items accepts 0 to 4, and index 5 is rejected. Python also accepts negative indexes such as -1, counting from the end, but stick to 0 to length - 1.

scores = [12, 7, 19, 4, 15]
print(len(scores))
print(scores[5])

Output:

5
IndexError: list index out of range (line 3)

Choosing a random item

To pick a random item, generate a random whole number from 0 up to the length minus one, then use it as the index. A list of seven items has indexes 0 to 6, so the number must run from 0 to 6: the lower bound is 0 because indexes start there, and the upper bound is length minus one because the length is one past the last item. Using 1 to length, or 0 to length, sometimes gives an invalid index and crashes the program.

Practise this