← Back to course
Code Crew G6+ / Week 05 / Wednesday
3/6
Week 05 Β· Lists and dictionaries

Wednesday

Looping through lists
// Keeping many values together
⏱ about 30 min

Wednesday: Looping through lists

Five temperature sensors send readings to Mission Control every hour. The weather team wants the highest, the lowest and the average, and they want them right now.

Rocket starts writing reading1, reading2, then stops himself. "No more numbered variables," he says. "These go in a list."

Raven nods at the screen. "What do you notice?" she asks. "We used for with range. Could for go through the list itself?"

Nova hums a short tune, one note per reading. "Interesting," she says. "A for loop can visit each item of a list in turn. And Python has tools that already know how to find the biggest and smallest."

Rocket types for t in temps and waits to see what happens.

for item in a list

for t in temps: runs the block once for each item. Each time round, t holds the next item. You choose the name; t is short for temperature.

Python also has built-in tools for lists of numbers: max() gives the biggest, min() the smallest, and sum() adds them all.

# readings.py
temps = [21, 19, 24, 22, 18]
for t in temps:
    print("Reading:", t)
print("Highest:", max(temps))
print("Lowest:", min(temps))
average = sum(temps) / len(temps)
print(f"Average: {average:.1f}")
Reading: 21
Reading: 19
Reading: 24
Reading: 22
Reading: 18
Highest: 24
Lowest: 18
Average: 20.8
If temps were [10, 20, 30], what would the Average line show?
WHY THIS EXERCISEsum is 60 and len is 3, so the average is 20.0 with one decimal place.

Numbering with enumerate

enumerate() gives you a counter along with each item. With start=1 the counter begins at 1, which is how people like to number things.

# checklist.py
checklist = ["Fuel", "Weather", "Crew", "Doors"]
for number, item in enumerate(checklist, start=1):
    print(f"{number}. {item}")
1. Fuel
2. Weather
3. Crew
4. Doors

Building a list from input

# pack.py
items = []
while True:
    item = input("Add an item (press Enter to finish): ").strip()
    if item == "":
        break
    items.append(item)
print(f"You packed {len(items)} items.")
for item in items:
    print("*", item)
Add an item (press Enter to finish): compass
Add an item (press Enter to finish): water
Add an item (press Enter to finish): 
You packed 2 items.
* compass
* water
READ THE LOOPS
  • Read the question.
  • Tap your answer.
In checklist.py, what is the third line of output?
In pack.py, what makes the loop stop?
At your computer
1. Type readings.py, save it and run it.
2. Add two more readings to the list and run it again.
3. Type pack.py, save it and run it. Add three items, then press Enter on an empty line.
4. Challenge: in pack.py, use enumerate to number the packed items.
# warm_days.py: keeps only the readings above 20
temps = [21, 19, 24, 22, 18]
warm = []
for t in temps:
    if t > 20:
        warm.append(t)
print("Warm readings:", warm)
print("How many:", len(warm))
PRACTICE: FILTER A LIST
  • Read the question.
  • Tap your answer.
What does warm_days.py show first?
Why does warm start as an empty list []?
Change t > 20 to t >= 21. Does the result change?
Which line would print each warm reading on its own line?
Change the test to t < 20. How many readings are kept?
What is sum(warm) in the original program?
What is max(temps)?
StatementTrue or false?
for t in temps gives t each reading in turn.?
min([4, 9, 2]) gives 9.?
sum([1, 2, 3]) gives 6.?
enumerate(items, start=1) numbers items starting at 0.?
WHY THIS EXERCISEmin gives the smallest, sum adds everything, and start=1 makes enumerate count from 1.

Loops and lists work beautifully together. Tomorrow you will meet dictionaries, which look things up by name instead of by position.

← Tuesday