Lists & Loops
Need to work with 30 test scores? You don't want 30 variables — or 30 copies of the same code.
Swipe or tap Next for the next section
One Name, Many Values
A list keeps many values together under one name. Each item has a position called its index. In this pseudocode, the first item is at index 1:
scores ← [72, 95, 88, 61] DISPLAY(scores[1]) DISPLAY(scores[3]) DISPLAY(LENGTH(scores))
That displays 72 (the first item), 88 (the third) and 4 (how many items there are). Lists can also change while a program runs:
- APPEND(scores, 80) adds 80 to the end.
- INSERT(scores, 2, 50) puts 50 at index 2 and shifts the rest along.
- REMOVE(scores, 1) takes out the first item and shifts the rest back.
Some languages count from 0 instead of 1 — always check which one you're using. Using an index that doesn't exist, like scores[5] in a list of four, is an error.
Loops: Repeat Without Rewriting
A loop runs the same steps again and again. There are three kinds you'll see:
- REPEAT n TIMES — when you know how many times.
- REPEAT UNTIL (condition) — when you stop once something becomes true.
- FOR EACH item IN list — once for every item in a list, in order.
Going through a list one item at a time is called traversing the list.
scores
Patterns Worth Knowing
Most list programs are one of a few patterns:
- Total — start at 0 and add each item.
- Largest or smallest — remember the best so far, and replace it when you find a better one.
- Count — start at 0 and add 1 whenever an item matches a condition.
- Filter — build a new list containing only the items you want.
Practice reading these with Pseudocode Practice, or see how lists get searched in Binary Search.
5 quick questions. Pick one answer for each — you'll see why straight away.
scores ← [70, 85, 90]. In this pseudocode, what is scores[1]?
In this pseudocode, lists start at index 1, so scores[1] is the first item.
What does LENGTH(scores) give for scores ← [70, 85, 90, 60]?
LENGTH counts how many items are in the list — here, four.
Why use a loop to add up 100 test scores, instead of 100 separate lines?
A loop repeats the same steps for every item. The code stays short, and it still works if the list grows to 1,000 scores.
total ← 0, then FOR EACH n IN [2, 4, 6] { total ← total + n }. What is total at the end?
0 + 2 = 2, then 2 + 4 = 6, then 6 + 6 = 12.
Which loop is the best fit for "keep asking for a password until it's correct"?
You don't know in advance how many tries it will take, so you repeat until a condition is true.