Grade 7 Computer Science · Lists

A list — many values under one name

Why a separate name for each value does not work, and what a list gives instead.

The variable that has no name

You can give each score in the class a separate name, as long as you know in advance how many students there are. Then a new student arrives mid-year, and the program cannot make a name for them while it runs. What can be added while it runs?

Until here every value had a name of its own. That works nicely for three values, becomes unwieldy at ten, and is impossible at a hundred — and above all, it breaks entirely when you do not know in advance how many values there will be. A list solves all three problems at once.

One name leads to all the values; the position chooses among them.
scores = [88, 92, 75]
print(len(scores))
scores.append(60)
print(len(scores))
The propertyWhat it makes possible
One nameGoing over everything in a loop
OrderReaching a value by its position
A changing sizeAdding and removing while running

Why this matters so much

Note what happened here: the list’s length is a value the program can ask about and respond to. In a loop over a collection we saw that the number of rounds comes from the collection and not from the code — now it is clear why that is so powerful. A program written correctly over a list works on three items and on three thousand without a line changing, because nowhere in the code is a number assumed. Every time you write a fixed number describing “how many there are”, it is worth stopping to ask whether it truly is fixed.

Example 1 — why separate names break

  1. Each value has its own name in the code.
  2. A further value arrives that was not expected.
  3. It has no name, and a name cannot be made while running.
  4. In a list it is simply added.

Example 2 — a length as a value

  1. The list is asked what its length is.
  2. An item is added to it.
  3. It is asked again and a larger number comes back.
  4. The code did not change, and the answer did.
Nowhere in the code is it written how many items there are — the program asks.