1. Model one record, then a collection
By the end
- Distinguish a list from a dictionary.
- Trace an accumulator through a loop.
A dictionary groups named facts about one session; a list holds the sessions in order. Choose keys with units when that prevents ambiguity. The value 30 means little until the key says minutes rather than hours.
An accumulator starts at zero before the loop and changes once per record. If it starts inside the loop, each iteration forgets the previous total. Trace the values on paper before relying on a printout.
Separate the input representation from the question. The same list can answer total minutes, the longest session or the number above a threshold. Keep the original records unchanged so you can inspect them if the summary looks wrong.
Worked example
Find total minutes for three sessions without changing their records.
- Start total at 0 outside the loop.
- Add 20, then 35, then 45: the running totals are 20, 55 and 100.
- Divide 100 by 3 only after the loop if a mean is needed.
sessions = [
{"day": "Mon", "minutes": 20},
{"day": "Tue", "minutes": 35},
{"day": "Wed", "minutes": 45},
]
total = 0
for session in sessions:
total += session["minutes"]
print(total) # 100The total is 100 minutes. The mean is 100/3, approximately 33.33 minutes; rounding is presentation, not a change to the data.
Try it yourself
Add a zero-minute session. Find the new total, count and mean, then count sessions of at least 30 minutes.
- Keep the zero-minute row in the count.
- Use >= 30, so a session of exactly 30 minutes would qualify.
Reveal the practice solution
The total stays 100; count becomes 4; mean is 25. Two sessions qualify (35 and 45). Initialize a separate long_count = 0 and increment it inside an if session["minutes"] >= 30 condition.
Watch for this mistake: A zero is an observed value, not a missing row. Dropping it changes the denominator and the meaning of the mean.
Sources and review date
- Python: Data structures
Lists, dictionaries and iteration. Checked: .
Explanations, examples and quiz questions are original KitForma material. These links support technical facts and curriculum alignment.