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.
scores = [88, 92, 75]
print(len(scores))
scores.append(60)
print(len(scores))| The property | What it makes possible |
|---|---|
| One name | Going over everything in a loop |
| Order | Reaching a value by its position |
| A changing size | Adding 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
- Each value has its own name in the code.
- A further value arrives that was not expected.
- It has no name, and a name cannot be made while running.
- In a list it is simply added.
Example 2 — a length as a value
- The list is asked what its length is.
- An item is added to it.
- It is asked again and a larger number comes back.
- The code did not change, and the answer did.