Quarry School

Build an ordered list — quick review

In plain words

A queue at a counter has a first person, a second and so on, and each person keeps a place in line.

Rule

A list is written as values between square brackets, separated by commas, and keeps them in order. a[i] gives the item at index i, counted from 0; a[-1] gives the last item; len(a) gives the number of items. An index from len(a) up raises an IndexError.

Step

  1. Write the items in order between square brackets, separated by commas.

  2. Number the items from 0 under the list as you trace it.

  3. Before reading an item, check its index against the length: in a list that is not empty, the largest index is one less than len(), and an empty list has no item to read.

  4. To read an item, use its number in square brackets after the list's name. Use -1 for the last item.

  5. To work through every item, write a for loop over the list.

Trap

The usual slip is counting from 1. In a list of 3 items, queue[3] is not the last item: it is past the end, and the program stops with an IndexError. Use queue[2], or queue[-1].

Square brackets do two jobs here. In ["Ada", "Ben"] they make a list; after a name, as in queue[0], they read an item.