Programs that Hold Many Values
Lists and their positions
Read a value out of a list by its position, count how many values a list holds, and work out which position the last value sits at.
So far every variable has held one value. A list holds many, under one name: the values are written between square brackets with commas between them, and they stay in the order they were written. To get one of them out you write the list's name and then, in square brackets, which one you want. That number is called the position, and the word for how many values the list holds is len.
Counting starts at nothing
The first value of a list is at position 0, not position 1. That is worth a moment rather than a shrug: the position is not which value it is, it is how far along the list it sits, and the first value sits no distance along at all. Everything else follows from that. A list of six values has its last value at position 5, because it is five steps along from the front. There is no value at position 6, and asking for one is an error rather than an empty answer. And len gives you the count, never the last position — the last position is always one less than the count.
Worked example
What does this program print?
prices = [30, 45, 60] print(prices[0]) print(prices[2] - prices[1])
Label the positions before reading anything: 30 is at 0, 45 is at 1, 60 is at 2.
Doing this on paper first is worth the ten seconds every time. Almost every mistake with lists is made in this step and then carried faithfully through the rest.
Try it together
Now one that works its own last position out. Trace this together.
letters = [8, 3, 5, 9, 4, 7] print(len(letters)) print(letters[len(letters) - 1])
Take the len first — everything on the last line waits on it.
1.How many values does the list hold, and so what does the second line print?
Have a go
Have a go on your own. What does this program print?
weights = [14, 22, 18] print(weights[1])
Ready to practise?
Eight questions on what you have just read. Nothing is timed, and you can play as many times as you like.