Unit 4
Lists and data
Store a pile of numbers in a list, then let a loop count, add, find the biggest and average them in a blink.
Read
Ask a list anything
Ananya keeps a rain gauge on her balcony in Pune. Every evening she writes down how many millimetres fell. After a week her notebook says:
12, 0, 5, 30, 0, 8, 9
Her brother asks four questions. How many days did it rain? Which day was the wettest? How much fell in all? What is the average per day?
With seven numbers you can answer by eye. But what about a year of readings, or a whole city's weather stations over ten years? Nobody wants to add 100,000 numbers by hand. A program can ask the same questions of a list of any size, and it never gets tired. That is what this unit is about: storing data in a list and asking it many questions cheaply.
The Python in this unit is short. If you have not met
forloops or functions yet, read the code like a recipe: each line is one instruction, run from top to bottom.A list keeps many values under one name
In Python you write a list with square brackets:
rain = [12, 0, 5, 30, 0, 8, 9]Each value sits in its own numbered box. The box number is called the index, and Python starts counting at 0, not 1.
rain[0]is12, the first reading.rain[3]is30, the fourth reading.len(rain)is7, the number of items. The last index is 6, one less than the length.
Asking for
rain[7]is an error, because there is no box 7.Built-in questions
Python already knows how to answer some questions about a list:
Question Code Answer for rainHow many readings? (count) len(rain)7 How much in all? (sum) sum(rain)64 Wettest day's amount? (max) max(rain)30 Driest? (min) min(rain)0 Average per day? (mean) sum(rain) / len(rain)64 ÷ 7 ≈ 9.14 The mean is the sum divided by the count. There is no single built-in word for it here, so you build it from two you have.
Looping: how the answers are really found
sumandmaxare loops that someone else wrote. Writing your own is how you learn what they do, and how you answer questions Python has no word for.A loop repeats the same instruction for every item. The most useful pattern keeps a running answer in a variable (an accumulator) and updates it once for each item:
total = 0 for r in rain: total = total + r print(total) # 64On each pass
ris the next value from the list. The figure showstotalgrowing: 12, then 12, then 17, then 47, and so on, until 64.Counting is the same pattern with a test inside. To count rainy days, add 1 only when the reading is above zero:
rainy = 0 for r in rain: if r > 0: rainy = rainy + 1 print(rainy) # 5Finding the biggest keeps the best value seen so far:
biggest = rain[0] for r in rain: if r > biggest: biggest = r print(biggest) # 30Notice that
biggeststarts asrain[0], the first real reading, and not as0. Here the difference does not show, but take winter temperatures[-3, -7, -1]. If you started at0, nothing in the list would ever beat it and the program would claim the warmest day was0, a temperature that never happened. Starting from a real item is always safe.Worked example: a different question, a different answer
Question. On the days it did rain, what was the average amount?
Plan. Build a second list holding only the wet days, then take its mean.
wet = [] for r in rain: if r > 0: wet.append(r) print(sum(wet) / len(wet))Steps.
wetstarts empty. The loop appends 12, 5, 30, 8 and 9, sowetis[12, 5, 30, 8, 9]. Its sum is 64 and its length is 5.Answer. 64 ÷ 5 = 12.8 mm.
The average over all seven days was about 9.14 mm and the average over rainy days is 12.8 mm. Neither is "wrong". They answer different questions, and a program makes it cheap to ask both.
Which day was wettest?
max(rain)gives the amount, 30. To get the day, you need the position:rain.index(max(rain)) # 3Index 3 is the fourth day. If the list starts on Monday, that is Thursday.
Common mistakes
- Value or index?
rain[3]is the item in box 3 (30), not "the item whose value is 3". - Off by one. A list of 7 items has indexes 0 to 6. The first item is
rain[0], notrain[1]. - Resetting the accumulator. If you write
total = 0inside the loop, it restarts on every pass and you only get the last value. Set it once, before the loop. - Dividing by zero. The mean of an empty list is
sum / 0, which crashes. Checklen(data) > 0first when the list might be empty. - Starting
biggestat 0. Fine for rainfall, wrong for temperatures, debts or anything that can be negative.
Try it: Change
rainto a list of your own: last week's screen minutes, marks in a subject, or the number of steps you walked. Work out the sum and the biggest by eye, then predict what the program prints before you run it. In the lab you can watch the loop step by step.Why this matters
The code for 7 readings is exactly the code for 7 million. You only change the list. That is why data detectives write programs: once the question is written down as a loop, you can ask it of any data, and change one line to ask a different question.
Lab
The loop stepper
Four short programs, each with a list of data. Pick the right starting value and the right test from the menus, then step through the loop and watch the variables change. Your program is right when it matches the true answer.
Your goals
- Choose the right starting value, test and update for a sum, a count, a biggest-value and a mean program.
- Step through each loop and see the variables change on every pass.
- Get the true answer from all four programs.
The interactive lab opens once you register. Register to do this.
Quick check
Lists and data check
Eight questions about lists and loops. Trace the code carefully, line by line.
1.A program has scores = [7, 9, 6, 8, 10]. What does scores[1] give?
Answer with a number
2.A list has 10 items. What is the index of the last item?
Answer with a number
3.What is the mean of scores = [7, 9, 6, 8, 10]?
Answer with a number
4.What number does this program print? ```python total = 0 for x in [3, 4, 5]: total = total + x * 2 print(total) ```
Answer with a number
5.temps = [-3, -7, -1]. Which first line makes the "biggest so far" loop give the right answer for any list of numbers?
- biggest = 0
- biggest = temps[0]
- biggest = 100
- biggest = len(temps)
Choose one
6.Put these lines in the order that counts how many values in data are above 10.
- count = 0
- if v > 10:
- for v in data:
- count = count + 1
Put these in order
7.Here is data = [5, 10, 15]. Which statements are true?
- len(data) is 3
- The value 15 is at index 3
- sum(data) is 30
- data[0] is the first item
Choose all that apply
8.With data = [2, 4, 6, 8], match each expression to its value.
- sum(data)
- max(data)
- len(data)
- sum(data) / len(data)
Match each to: 5 · 20 · 8 · 4
Answering and checking are for registered learners. Register to do this.
Quick check
New puzzles with lists
Use loops and summaries in situations the reading did not show. Trace the code, do not guess.
1.A teacher's marks are [40, 55, 70, 85, 100]. How many marks are above the mean?
Answer with a number
2.What number is best when this finishes? ```python data = [3, 8, 2, 9, 4] best = 0 for i in range(len(data)): if data[i] > data[best]: best = i ```
Answer with a number
3.A student wants the mean of data = [2, 4, 6] but wrote this. What does it print? ```python total = 0 for x in data: total = 0 + x print(total / len(data)) ```
Answer with a number
4.temps = [-2, 5, 3, -1, 8]. A program keeps only the temperatures above 0 and takes the mean of those. What is the mean, to 2 decimal places?
Answer with a number
Answering and checking are for registered learners. Register to do this.
Your turn
The canteen sales list
A school canteen records how many samosas it sold on five days:
sales = [48, 52, 0, 61, 59]The 0 is a day the canteen was closed for a holiday.
- Write Python that uses a
forloop (not the built-insum) to find the total sold. Then write the mean per day. Give both answers. - The canteen manager wants "the average on days we were open". Write code that builds a list of the open days and finds that mean. Give the answer and explain in one or two sentences why it differs from your answer to part 1.
- In your own words, explain why writing the question as a loop is useful when the list has 5,000 items instead of 5. What would you change to ask a different question?
How it's judged
- Loop and accumulator
- Filtering for a different question
- Explaining why programs help
Writing and submitting your answer is for registered learners. Register to do this.
- Write Python that uses a
Like what you see?
Register for free to answer the quick checks, do the activities and save your work. Your work is saved on your device and syncs to your account.