Skip to content
Programming Data structures
All classes Beginner About 15 min Premium

Lists and their positions

Keep a shopping list in a program. Read an item by its index, change one, add and remove items, and find out what happens when you ask for an index past the end of the list.

Core concept

A list (array) keeps items in order; each item has an index, counted from 0, so a list of n items has indexes 0 to n − 1

Topic: Data structures

A list keeps many items under one name, in order, like a shopping list on a piece of paper. Each item has a position number called its index. Programs start counting at 0, so the first item is at index 0, the second at index 1, and so on. A list of 3 items has indexes 0, 1 and 2, and no index 3. We can read an item (shopping[1]), change it (shopping[1] ← "Milk"), add one at the end (append) or at a position (insert), and remove one (remove). When an item is added or removed, the items after it move up or down one place, so their indexes change.

Key words explained

What you will learn

  • Read and change an item using its index.
  • Explain why the first item is at index 0 and the last at index n − 1.
  • Add and remove items and predict how the other indexes change.
  • Recognise an index that is out of range.

Before you start

  • Know what a variable is.

Materials

  • A notebook to write the list after each change

Equipment

  • None

Procedure

  1. Choose index 1 and press Get to read an item.
  2. Choose Milk, index 1, and press Set to change it.
  3. Add Salt at the end with Append.
  4. Ask for an index past the end and read why it is refused.
Premium experiment Create a free account