Class 9 · Unit 5: Python · Lesson 5.5 · 40 min
Lists, and doing something to every item
Five days, five variables. Then the teacher asks for a month: thirty-one variables. There's a better box.
Today you will: Store many values in one list · Do something to every item with a loop · Build a running total and a mean
Story
Hiba has five temperatures on the board — Monday to Friday — and a program with five variables in it: mon, tue, wed, thu, fri. It works. She is pleased with it.
Then her teacher asks for the average across a month.
Thirty-one variables. Thirty-one lines of typing, and thirty more + signs. She has written the same instruction over and over, which is exactly what a computer is supposed to do for her.
There is a better container, and a way to say do this to every item in it.
Watch
One name, many values — — scan code 9.5.5 in the printed book.
Learn it
Five days means five variables; a month would mean thirty-one. A list keeps many values under one name, and a loop does the same thing to every item in it, so the program stays the same length whether there are five values or five thousand. This is the shape data really has: every model you trained this year learned from a list of examples, not from one.
Words to know
- List many values under one name, in square brackets:
marks = [72, 58, 90]. - Index an item's position. Positions start at 0, so
marks[0]is72. - len(list) how many items there are. The last position is
len(list) - 1. - IndexError asking for a position beyond the end of the list.
- for loop
for item in list:runs the indented lines once for each item, in order. - += / -= add to / take away from what a variable already holds:
total += 5meanstotal = total + 5. - Running total a variable set to 0 before the loop, with each item added inside it.
- while loop repeats as long as a condition is true. If nothing ever makes it false, it is an infinite loop.
Step by step: the average of a week's rainfall
rain = [4, 0, 12, 7, 2]
total = 0
for r in rain:
total += r
print(total) # 25
print(total / len(rain)) # 5.0
- The list: 5 days of rainfall in mm.
rain[0]is4;rain[4]is2;rain[5]is an IndexError. - Before the loop:
total = 0, an empty pot. - Each time round:
rtakes the next value, andtotal += radds it: 4, 4, 16, 23, 25. - The mean: total ÷ how many = 25 ÷ 5 = 5.0 mm.
- Check it in one line:
sum(rain) / len(rain).
Careful: put total = 0 inside the loop and it resets every time, leaving only the last
value. And len is the count, not the last position: in a list of 5, the last item is
rain[4], and asking for rain[5] is an IndexError.
On the laptop
You need: Thonny · save as 05-average.py
Mission 1: A list and its positions (6 min)
- ☐1
Predict the four outputs first, then run:
temps = [12, 15, 18, 21, 19] print(temps) print(temps[0]) print(temps[4]) print(len(temps)) - ☐2
Predict: what will
print(temps[5])do? Run it:IndexError: list index out of range. Positions start at 0. Delete the line.
Mission 2: Every item, in turn (8 min)
- ☐3
A running total, then the mean:
total = 0 for t in temps: total += t print("Total:", total) print("Average:", round(total / len(temps), 1))total += tmeans addtto what's already intotal. You should get 85 and 17.0. - ☐4
Check it in one line:
print(sum(temps) / len(temps)).
Mission 3: Repeat until something changes (4 min)
- ☐5
A
whileloop runs as long as a condition is true:count = 5 while count > 0: print(count) count -= 1 print("Done")Forget
count -= 1and it runs for ever — press Stop. Every programmer does it once. Save: five programs kept.
Stuck?
IndexError? Count from zero. Total always 85? total = 0 must be above the loop. Won't
stop? A while with no -= 1 — press Stop. Only the last number prints? Check the
indentation.
Finished early?
Find the highest temperature without max(): start with highest = temps[0], loop, and
replace it whenever you meet a bigger one. Check against max(temps).
No laptop today?
Trace the running total on paper in two columns, t and total, one row per time round. How
many rows, and why? What would print for a one-item list, [12]?
Debate it
To find the average, the program needed all five numbers, not one.
A model that grades apples needs many photographs; a model that predicts rainfall needs many years. But somebody chooses which five days, or which five hundred photographs, go into the list. Who is left out of a list, and what does that do to the average? You have answered a version of this question every year since Class 6 — say what has changed in your answer.
Check yourself — practice, not a test
1. In temps = [12, 15, 18, 21, 19], what does temps[1] give?
- ○ 12
- ○ 15
- ○ 1
- ○ 19
2. What does this print? python nums = [4, 6, 10] total = 0 for n in nums: total += n print(total)
- ○ 0
- ○ 20
- ○ 10
- ○ 4 6 10
3. Find the bug. This should print the total, but prints 10: python nums = [4, 6, 10] for n in nums: total = 0 total += n print(total)
- ○ The list is wrong
- ○ total = 0 is inside the loop, so it resets each time
- ○ += should be =
- ○ print should be indented
4. len([3, 5, 7]) gives 2, because counting starts at zero.
- ○ True
- ○ False
5. A loop that never ends because its condition stays true is called an ______ loop.
6. Put these in the order they must appear to total a list correctly:
- 1. for n in nums:
- 2. total = 0
- 3. print(total)
- 4. total += n
Remember
A list holds many; a loop visits each one. Count from zero, and set the pot to 0 first.
Typing practice
Today's symbols are the square brackets [ ] and the comma ,.
[and]are to the right of P. No Shift — that is what makes them different from{and}.- typing.com: the symbols lessons, then a free practice round.
- Then type this line four times, with no mistakes:
temps = [12, 15, 18, 21, 19]
You have now met every symbol this unit needs: ( ) " " _ = : [ ] and the
operators. From here the difficulty is thinking, not typing.