Menu

Data Types and Structures

Arrays Lists

Contents

  1. Python Lists
  2. List Indexes and Length

A Python list gives you array-style storage: one name holds a collection of related values. You create one with square brackets, separating the items with commas.

In a standard array, every item must be the same data type, and the length is fixed when the array is created. A Python list is more flexible: it can store different data types, although keeping to one type is advised so the values are easier to process, and it has no fixed length.

FeatureStandard arrayPython list
Data typesEvery item must be the same typeCan mix types, but one type is advised
LengthFixed when createdCan change while the program runs
Adding to the endCannot grow; you may need a larger array and copy the items acrossappend adds an item to the end

Creating and adding items

A list can be created empty (scores = []) or with initial items (scores = [12, 8, 15]). The append operation adds a new item to the end, making the list one item longer. A standard array cannot grow beyond its fixed length, so adding more items may mean creating a larger array and copying the existing items across. A Python list avoids that limitation.

Why lists are useful

Lists are useful when many related values need the same operation. One identifier and a loop can handle all the values, so you avoid many separate variables and repeated code. A loop can input, process, search, sort or output every item without writing separate code for each variable, which makes lists natural for large groups of related data.

For example, you can keep daily step counts in one list, append today's count, then use a loop to add every count to a running total.

daily_steps = [4200, 6100, 3800]
daily_steps.append(5500)

total_steps = 0
for steps in daily_steps:
    total_steps = total_steps + steps

print(total_steps)

Output:

19600

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.

Also useful