lesson

An index identifies a position

1 · Learn

A list stores an ordered collection. In Python, the first item has index 0. For colours = ['red','blue','green'], colours[1] is 'blue' and len(colours) is 3. A valid non-negative index here is less than the length.

The number of items and the final index are different. Trying to use index 3 in this three-item list is outside the range. Empty lists need explicit handling rather than assuming a first item exists.

Index 0: redIndex 1: blueIndex 2: greenLength: 3
Key words and supplied examples.

2 · Worked example

I access the last item using a known valid index or a suitable language feature, rather than treating len(colours) as the final non-negative index.

3 · Your turn

For scores = [4,9,6,2], what is scores[2] and what is the list length?

Check your answer

scores[2] is 6; the length is 4.

4 · Apply your learning

Trace a loop through a small list and test an empty list, a one-item list and a longer list.

Adult guidance and safety

Use an approved private interpreter, simulator or authoring tool with fictional data. Trace and predict before running. Never execute unknown downloaded code, inspect real credentials or use other people's private data. Working examples still need saved-project and assessment integration before release.

Practice this lesson

Lesson resources

Browse the available practice activities and worksheets for this lesson.

Open course resources
Exercise preview