Lists: many values under one name
A list holds several values in order under one name, written between square brackets: scores = [12, 7, 9]. Each item has an index, its position, and counting starts at 0: scores[0] is 12, scores[1] is 7, scores[2] is 9. A negative index counts from the end, so scores[-1] is 9. len(scores) gives the number of items, 3. scores.append(15) adds an item at the end, and scores[1] = 8 replaces the item at index 1. After these two changes the list is [12, 8, 9, 15]. remove(9) deletes the first item with that value, and pop() removes and gives back the last item. To visit every item, use for x in scores. To collect a result we use a variable that is built up as the loop runs: total = 0 and then total = total + x for each x gives the sum 44; best = scores[0] and then replace best whenever a bigger x is found gives the largest, 15. Python also has ready tools, sum(scores) and max(scores), that give the same results; writing the loop by hand once helps you understand them. Do not name your own variables list, sum or max, because the name would hide the tool.
| index | 0 | 1 | 2 | 3 |
|---|---|---|---|---|
| value | 12 | 8 | 9 | 15 |
1scores = [12, 7, 9] 2print(scores[0]) 3print(scores[-1]) 4print(len(scores)) 5scores.append(15) 6scores[1] = 8 7print(scores)
12 9 3 [12, 8, 9, 15]
1scores = [12, 8, 9, 15] 2best = scores[0] 3for x in scores: 4 if x > best: 5 best = x 6print(best) 7print(sum(scores), max(scores))
15 44 15
1scores = [12, 8, 9, 15] 2scores.remove(9) 3last = scores.pop() 4print(last) 5print(scores)
15 [12, 8]
On paper, write a list of five numbers of your choice (for example the ages of five invented characters). Draw it as boxes with indexes 0 to 4, then write the result of len, of the first item, of the last item with index -1, and of a loop that adds them all.