Lists and Dictionaries
Changing and growing a list
Work out what a list holds after values have been added on the end, written over, or joined on from another list.
A number handed to a variable is finished with: to change it you work out a new number and put that in instead. A list is not like that. It is a thing a program keeps hold of and adjusts as it goes — a queue that grows as people join it, a set of readings that grows as they are taken. There are three ways this course changes one. A value can be added on the end. A value already in the list can be written over. And two lists can be joined into one with a plus sign, which leaves both of the originals as they were and makes a new list holding everything from the first followed by everything from the second.
Adding on and writing over are different jobs
Appending puts a new value on the end and makes the list one longer. Writing to a position replaces what is already there and leaves the length exactly as it was. Muddling the two is the commonest mistake with lists, and it goes wrong in a particular direction: you cannot add a value by writing to a position that does not exist yet. A list of four values has positions 0 to 3, so writing to position 4 is not "adding a fifth" — it is asking to change something that is not there, and the program stops rather than guessing what you meant.
Worked example
What does this list hold once both of the changes have been made?
stack = [2, 5, 5] stack[2] = 8 stack.append(1)
Start by writing the list out as the first line leaves it: 2, 5, 5.
A list that is about to change twice is worth writing down once. Every mistake after this point comes from working on a list you are only half remembering.
Try it together
Now follow one list through three changes in a row.
row = [6, 1] row.append(4) row[0] = 9 row = row + [3, 8]
Take one line at a time, and write the list out again after each one before you go on.
1.The second line appends a 4. At which position does that 4 land?
Have a go
Have a go on your own. A list holds three values. A program adds one value on the end and then writes over position 0. Which of these describes the list afterwards?
Ready to practise?
Eight questions on what you have just read. Nothing is timed, and you can play as many times as you like.