Keep Readings in a List
Replace four separate reading names with one ordered list and count its values with len(). Use the list only as a shared source for the repetition that follows.
The Chapter 2 report gave every reading a separate name:
That works for four fixed values, but it becomes awkward when a measurement has many readings. A list keeps an ordered sequence of values under one name:
readings = [18, 21, 20, 23]
The square brackets make a list literal. The commas separate its values. The order is part of the data: this list records 18 first, then 21, then 20, then 23.
Keep One Ordered Sequence
The name readings refers to the whole sequence, not to just its first value.
We can display the list as one value:
The output is:
[18, 21, 20, 23]
For now, treat the list as one ordered source of readings. We will not pick out individual positions or change the list yet. Chapter 5 returns to lists as data structures and develops those operations carefully.
Q1. Read the sequence
Which values, in order, does this list contain?
readings = [18, 21, 20, 23]
Select one choice, then check.
HintDo not rearrange the values
The list has not sorted or added its values.
SolutionThe original order remains
The list contains 18, 21, 20, and 23 in exactly that order.
Count the Readings
The built-in function len() reports how many values are in a list:
The output is:
4
len(readings) produces the number 4. It does not calculate the total or the
mean; it answers only how many readings the sequence contains.
Q2. Count a new list
What value does len(readings) produce here?
readings = [19, 20, 18]
Select one choice, then check.
HintCount values, not their size
There are three numbers between the brackets.
SolutionThe length is 3
len() counts entries in the list. This list has 19, 20, and 18, so its
length is 3.
Prepare to Visit Every Value
A list gives a for loop one visible sequence to work through. The next lesson
will explain this syntax one part at a time:
For this list, the loop will print the readings in their stored order:
18
21
20
23
At this point, the important idea is the relationship: readings holds the
values, and a later loop can visit them one by one. We do not need a separate
name or a separate print instruction for every measurement.
Q3. Create the shared source
Complete the assignment so that readings contains the four measurements in
their recorded order: 18, 21, 20, and 23.
Editable Python
Ready to run.
HintUse a list literal
Replace the empty brackets with the four numbers, separated by commas.
SolutionStore the readings in one list
readings = [18, 21, 20, 23]
A list keeps related values in one visible order, and len() tells us how
many it contains. Next we will use a for loop to perform one action for each
reading.