Lists
How to read, change, insert, append, and remove list elements by index, how to walk through a list with FOR EACH, and the standard list algorithms: largest, smallest, sum, average, and linear search.
1A list and its indexes
A list is an ordered collection of elements stored under one name. Each element has an index, its position number. In the reference language the first element is at index 1, not 0, and the last is at index LENGTH(aList).
Using an index less than 1 or greater than the length of the list is an error, and the program stops. For pets ← ["cat", "dog", "fish"], pets[3] is "fish", but pets[4] and pets[0] both end the program.
Programming languages spell these list operations differently (some count from 0, some use brackets, some use named commands), but the ideas below are the same everywhere.
2Reading and writing elements
| Code | What it does |
|---|---|
x ← aList[i] | Copies the element at index i into the variable x |
aList[i] ← x | Replaces the element at index i with the value of x |
aList[i] ← aList[j] | Copies the element at index j into index i; index j is unchanged |
LENGTH(aList) | The number of elements in the list right now |
pets ← ["cat", "dog", "fish", "bird"] x ← pets[2] DISPLAY(x) pets[4] ← "frog" pets[1] ← pets[3] DISPLAY(pets) DISPLAY(LENGTH(pets))
This displays dog, then [fish, dog, fish, frog], then 4. Replacing an element never changes the length, and copying pets[3] into pets[1] leaves two copies of "fish".
3Insert, append, remove, length
| Procedure | What happens to the list |
|---|---|
INSERT(aList, i, value) | Elements at index i and after shift one place right; value goes in at index i; length goes up by 1 |
APPEND(aList, value) | value goes on the end; length goes up by 1; nothing shifts |
REMOVE(aList, i) | The element at index i is removed; elements after it shift one place left; length goes down by 1 |
The shifting is where traces go wrong. After an INSERT at index i, the element that was at i is now at i + 1. After a REMOVE at i, the element that was at i + 1 is now at i. Watch one list go through five operations:
names ← ["Ana", "Ben", "Cy"] INSERT(names, 2, "Dev") APPEND(names, "Eli") REMOVE(names, 1) names[3] ← "Fay"
At the end, names is [Dev, Ben, Fay, Eli]. Notice that the last line changed index 3, which held "Cy" only because REMOVE had moved Cy there. An index you used two lines ago may point to a different element now.
4Walking a list with FOR EACH
Going through the elements of a list is called traversing it. Iteration statements can traverse a list, and the reference language has a loop made for it:
FOR EACH item IN aList
{
<block of statements>
}
The variable item is given the value of each element in order, from the first to the last, and the block runs once for each. You do not manage any index.
temps ← [61, 58, 70, 66]
FOR EACH t IN temps
{
DISPLAY(t - 50)
}
This displays 11 8 20 16: one line per element, in list order. A traversal that looks at every element is a complete traversal; one that looks at only some of them (for example, stopping once it finds what it wants) is a partial traversal.
5Standard list algorithms
Two traversals come up so often that they are worth knowing by heart, because new list algorithms are usually built from them.
Largest (or smallest) value. Keep the best value seen so far, and replace it whenever an element beats it:
best ← nums[1]
FOR EACH n IN nums
{
IF (n > best)
{
best ← n
}
}
DISPLAY(best)
| n | n > best? | best afterward |
|---|---|---|
| -4 | no | -4 |
| -9 | no | -4 |
| -1 | yes | -1 |
For [-4, -9, -1] it displays -1. Start best at the first element, not at 0: with best ← 0 this list of negative numbers displays 0, a value that is not even in the list. For the smallest value, flip > to <.
Sum or average. Add each element to a running total, then divide by the length:
total ← 0
FOR EACH n IN nums
{
total ← total + n
}
DISPLAY(total / LENGTH(nums))
For [88, 72, 95, 81] the total is 336 and it displays 84.
6Linear search
A linear search (also called a sequential search) checks each element of a list in order until it finds the value it wants or has checked every element. This procedure returns the index of the first match, or −1 if there is none:
PROCEDURE findIndex(aList, target)
{
i ← 1
REPEAT UNTIL (i > LENGTH(aList))
{
IF (aList[i] = target)
{
RETURN(i)
}
i ← i + 1
}
RETURN(-1)
}
| Search for | Returns | Elements checked |
|---|---|---|
| 42 | 1 | 1 |
| 33 | 4 | 4 |
| 99 | -1 | 6 |
RETURN ends the procedure at once, so a value near the front is found fast. A value that is not there costs a check of every element. A linear search works on any list, sorted or not.
Lists start at index 1. INSERT and REMOVE shift the elements after them; APPEND adds to the end. FOR EACH visits every element in order. The largest/smallest, sum/average, and linear search algorithms are all traversals, complete or partial.
7Changing a list while you walk it
Removing elements inside a loop that counts up through the indexes skips elements. This loop is meant to remove every even number:
i ← 1
REPEAT UNTIL (i > LENGTH(nums))
{
IF (nums[i] MOD 2 = 0)
{
REMOVE(nums, i)
}
i ← i + 1
}
DISPLAY(nums)
For [2, 4, 5, 6] it displays [4, 5]; the 4 survived. When 2 was removed from index 1, the 4 shifted into index 1, but i had already moved on to 2. The fix is to move to the next index only when nothing was removed:
i ← 1
REPEAT UNTIL (i > LENGTH(nums))
{
IF (nums[i] MOD 2 = 0)
{
REMOVE(nums, i)
}
ELSE
{
i ← i + 1
}
}
DISPLAY(nums)
Now it displays [5]. Another safe way is to build a new list with APPEND instead of removing from the old one.
8Worked examples
Three changes
What is displayed?
L ← [4, 8, 15] INSERT(L, 2, 6) REMOVE(L, 4) L[1] ← L[3] DISPLAY(L)
- 1Start: [4, 8, 15]. INSERT at 2 shifts 8 and 15 right: [4, 6, 8, 15].
- 2REMOVE index 4 takes out 15: [4, 6, 8].
- 3
L[1] ← L[3]copies 8 into index 1: [8, 6, 8].
[8, 6, 8]Count a word
Write code that displays how many times the word "the" appears in the list words, and trace it on [the, cat, and, the, hat].
- 1Use a complete traversal with a counter that goes up on a match:
count ← 0 FOR EACH word IN words { IF (word = "the") { count ← count + 1 } } DISPLAY(count) - 2The matches are elements 1 and 4.
2.Prices under $20
What does this display for prices = [25, 12, 19, 40, 20, 8]?
result ← []
FOR EACH p IN prices
{
IF (p < 20)
{
APPEND(result, p)
}
}
DISPLAY(result)
- 1
result ← []starts an empty list. - 2Each price under 20 is added to the end with APPEND: 12, then 19, then 8. 20 is not under 20.
[12, 19, 8]. The original list is unchanged.Doubling every element
Both segments try to double every element of nums = [1, 5, 7]. What does each display?
FOR EACH n IN nums
{
n ← n * 2
}
DISPLAY(nums)
i ← 1
REPEAT LENGTH(nums) TIMES
{
nums[i] ← nums[i] * 2
i ← i + 1
}
DISPLAY(nums)
- 1In the first,
nis a copy of each element. Changingnchanges only the copy, so the list is untouched. - 2The second writes back into the list by index:
nums[i] ← nums[i] * 2.
[1, 5, 7]. Second: [2, 10, 14]. To change elements, assign to nums[i].9Common mistakes
The first element is aList[1]. aList[0] is an error, and so is any index above LENGTH(aList).
After INSERT or REMOVE, the elements after that index have new positions. Redraw the list after every change.
If every value is negative, the answer comes out as 0. Start with the first element of the list.
The loop variable is a copy of each element. Assigning to it does not change the list; assign to aList[i] instead.
“The code traverses the whole list with FOR EACH. It keeps the largest value seen so far in best, which starts at the first element, and replaces it whenever an element is larger. After the loop, best holds the largest value in the list.”
Say how the list is traversed, what each pass does, and what the variables hold at the end.