Specialty Digest

Global English editionLearners’ Study Dashboard — in development
The Knowledge Library for All

Flashcards: open the module flashcards (end-of-module review with workplace questions).

Online Courses / University Track / Python from Zero

Module 4 · Lesson 2 · Core

Looping over lists: totals, search and sorting

Use a loop to visit every item, then total, search, find the largest and sort.

  • 50 minutes
  • Serves O4
  • Assumes M4.L1

Phase 1: Prepare

Step 1 Warm-up recall

From M4.L1: what position does the first item have?

Private: nothing you type here is sent or stored.

Step 2 Learning goal

By the end of this lesson you can:

  • loop over a list with for (Foundation);
  • total, average and search (Core);
  • use sum, max, min and sorted (Core).

Phase 2: Teach

Step 3 A familiar example

A teacher goes through a pile of marked scripts one by one, keeping a running total and noting the highest mark. A loop over a list does the same.

Step 4 Clear explanation

A for loop can walk straight through a list, with no need for positions:

scores = [70, 85, 60, 90]
total = 0
for s in scores:
    total = total + s
print(total)
print(total / len(scores))
305
76.25
Starttotal = 0Visiteach itemUpdateadd or compareUseafter the loop
A loop over a list visits every item; a total, a largest value or a search result is built up as you go.

Python has short tools for common jobs. sum(scores) gives 305, max(scores) gives 90, min(scores) gives 60 and sorted(scores) gives [60, 70, 85, 90] without changing the original.

To search, keep a flag that starts False and set it to True when an item passes the test:

found = False
for s in scores:
    if s > 80:
        found = True
print(found)
True

Take care with the range of items. If a calculation leaves out some items, the answer is wrong without any error message, so check how many items a loop really visits.

Step 5 Worked example (4 marks)

For nums = [4, 9, 2] find sum, max and sorted.

  1. sum: 4 + 9 + 2 = 15. (1 mark)
  2. max: the largest is 9. (1 mark)
  3. sorted: [2, 4, 9]. (1 mark)
  4. Answer: 15, 9 and [2, 4, 9]. (1 mark)

Go deeper: the professor's notes

When you loop over a list, check how many items the loop really visits.
Total

Add each.

Count

len(list).

Check

First and last.

Starttotal = 0Visiteach itemCountitemsCompareexpected
Loop

Count

Items inItems used
1010 good
105 bad

At work: An average

The average is based on a list.

  1. Print len(list).
  2. Compare with the source.

What a careful practitioner decides. Always compare the count in with the count used.

Phase 3: Practise

Step 6 Learner practice (instant-marked)

1. sum([2, 3, 5]) is:

2. max([4, 9, 2]) is:

3. sorted([3, 1, 2]) gives:

4. The average of [70, 85, 60, 90] is:

Phase 4: Close

Step 7 Recap

  • for s in scores visits every item.
  • sum, max, min and sorted do common jobs.
  • Check how many items the loop really covers.

Step 8 Exit ticket (ungraded)

Write a loop that finds how many items in [5, 12, 8, 20] are over 10.

Private: nothing you type here is sent or stored.

Step 9 Go further (Extension)

Write a program that prints the largest mark without using max.

In industry: A range that stopped short

A coding error in a working spreadsheet left five countries out of an average used in a widely cited 2010 economics paper. A student found it in 2013 when he obtained the spreadsheet.

Link to this lesson. When you total or average a list, check how many items you really included.

Source: Herndon, Ash and Pollin (2013), PERI; New Statesman, 17 April 2013

Common mistakes

MistakeWhy it fails
Dividing by the wrong countUse len(list).
Leaving items out of the loopCheck the first and last item.
Expecting sorted to change the listIt returns a new list.

Limits. Large lists of decimals can show tiny rounding differences when summed.

Flashcards for this lesson (3)

Tap a card to reveal the answer. Read the question, answer it aloud or in writing first, then check yourself against the explanation.

Card 1 of 3 · How do you add to a list?
List[1, 2]append3Result[1, 2, 3]
append

Use append, which adds one item at the end and changes the list in place. For example, add each new order to an orders list.

Card 2 of 3 · How do you total and average a list?
sumtotallencountDivideaverage
Average

sum gives the total and len the count, so the average is sum(list) / len(list). Check that you used all the items.

Card 3 of 3 · How do you find the largest, smallest and sorted values?
maxlargestminsmallestsortednew list
max, min, sorted

max and min give the extremes, and sorted gives a new list in order. They save writing loops for common jobs.

Review with flashcards

Test yourself on this module with workplace flashcards and detailed answers.

Open the module flashcards