List Functions & Indexing
If all data is static then progress has failed
Lists would not be very useful if we could only create them. CSP provides ways to add items, remove items, and read or change the item at a particular position.
Indexing
Every item in a list has a position, called its index. CSP uses 1-based indexing, so
the first item is at index 1, the second is at index 2, and so on. We read an item by
placing its index in square brackets after the list.
- Index (noun)
- An item’s position in a list
This displays one and then three.
Many programming languages start counting at
0. In CSP, the first item is always at index1. There is no index0.
Using an index that does not exist, such as list[4] in a three-item list, is an error.
Changing an Item
We can replace an item by assigning to its index with the same arrow we use for variables.
The list is now [20, "two", "three"]. Since lists can mix types, it does not matter
that the old value was a string and the new one is a number.
Assigning to the End
We can also assign to the index one past the end of the list. This adds a new item to the end.
The list now has four items. This is also how we fill an empty list, which we write as
[].
We can only assign to an index that already exists or to the index directly after the last item. There cannot be gaps in a list.
Length
The LENGTH function returns how many items are in a list.
This displays 3. Since indices start at 1, the last item of a list is always at index
LENGTH(list).
- Indices (noun)
- Plural of index
LENGTH also works on strings, where it returns the number of characters.
This displays 11. The space counts as a character.
Changing the Size of a List
Three functions change the list they are given. They are used as their own lines of
code, not inside DISPLAY.
APPEND
APPEND(list, value) adds a value to the end of the list.
The list is now ["one", "two", "three", 4].
INSERT
INSERT(list, index, value) adds a value at the given index. The item that was there,
and every item after it, moves one position toward the end.
The list is now [true, "one", "two", "three", 4]. Inserting at index 1 puts the new
value at the front.
Note the difference from assigning. list[1] ← true would replace the first item.
INSERT(list, 1, true) adds a new item and keeps all the old ones.
REMOVE
REMOVE(list, index) deletes the item at the given index. Every item after it moves one
position toward the front.
This removes "two", so the list is now [true, "one", "three", 4].
Because items shift after an INSERT or REMOVE, an index that pointed to one item a
moment ago may now point to a different one.
Putting It Together
We can combine these tools with a FOR EACH loop. This program builds a list of the even
numbers from another list.
The evens list starts empty. Each even number is appended as it is found, so the
program displays 3.
Remember that a list cannot be displayed directly. To see what is inside evens, we loop
over it.
Next: Procedures