Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Free lesson

2.3 (3 of 3): Build and debug with lists and dictionaries

The whole lesson, free. Read it and have a go at the activities. To work the tasks and labs in the real lesson, press Start lab, with no account needed.

45 minutes

A quick check that you are not a bot, then your own lab opens on the interactive lesson.

Already have an account? Sign in

The scoreboard shows nothing

You build a scoreboard. You sort the scores and print the result. The screen says None.

No error message. Just None. Where is the mistake? Many bugs with lists and dictionaries look like this. This lesson shows you how to spot them.

Key words

WordWhat it meansExample
DebugFind and fix mistakes.change len(items) to len(items) - 1
IndexErrorYou asked for a list position that does not exist.items[5] in a list of 3
KeyErrorYou asked for a dictionary key that does not exist.menu["pie"] with no pie
Off by oneA mistake where an index is one too big or one too small.items[len(items)]
ListOne name that holds many values in order.[1, 2, 3]
DictionaryA data structure of keys and values.{"tea": 2}
IndexThe position number in a list. It starts at 0.0
FunctionA named piece of code that does one job.max(scores)

The cells students fill in are left blank in this preview.

Try it: the sort surprise

Code: python
scores = [30, 10, 20]

result = scores.sort()
print(result)
print(scores)

# sort() changes the list itself. It gives back None.
# Fix: sort, then print the list.

Make a free account to save your work and track your progress.

The five mistakes you will meet

MistakeWhat you seeThe fix
Index too big (off by one)IndexError: list index out of rangeThe last index is len(items) - 1
Missing keyKeyError: the keyCheck with in first
Using the result of sort()None is printedCall sort(), then use the list
Adding in the wrong placeThe new item is at the end, not the startUse insert(0, item) for the start
Mixing up index and valueThe wrong item or an errorSay aloud: position or value?

The cells students fill in are left blank in this preview.

Spot the mistake

Have a go

Spot the mistake

3 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Try it: insert, append and pop

Code: python
a = [1, 2]
a.append(3)
print(a)

a.insert(0, 9)
print(a)

last = a.pop()
print(last)
print(a)

# append adds at the end.
# insert adds at an index.
# pop takes the last one out.

Make a free account to save your work and track your progress.

Try it: fix the bug

Code: python
items = ["tea", "cake", "pie"]

last = items[len(items)]
print(last)

# This stops with an IndexError.
# Change the index so it prints pie.

Make a free account to save your work and track your progress.

Watch: read the error, then fix it

You have run the sort surprise and fixed the bug. Press Play on the short film below: each mistake comes first, then its fix.

Film: debugging, read the error then fix it

Debugging: read the error, then fix it

Every scene, as text

  1. Myth (false): the last index is len(items). items = ["tea", "cake", "pie"] has indexes 0, 1 and 2, but len(items) is 3, so last = items[len(items)] stops with IndexError: list index out of range, and the error names that line.
  2. Debug: find and fix mistakes. The last index is len(items) - 1, which is 2, so after last = items[len(items) - 1], print(last) shows pie.
  3. Myth (false): sort() gives a sorted list. With scores = [30, 10, 20], result = scores.sort() sorts scores itself and gives back None, so print(result) shows None, with no error message.
  4. The fix: call sort(), then use the list. scores.sort() puts scores itself in order, lowest first, so print(scores) shows [10, 20, 30].
  5. The error's name says where to look. With the same items, print(items[3]) stops with IndexError: list index out of range: a list position that does not exist.
  6. With menu = {"tea": 2}, print(menu["pie"]) stops with KeyError: 'pie': a dictionary key that does not exist. So check with in first: print("pie" in menu) shows False.

Extra: Try it: two names, one list

Code: python
a = [1, 2]
b = a
b.append(3)
print(a)

c = a.copy()
c.append(4)
print(a)
print(c)

# b = a gives the same list a second name.
# So a changes too.
# copy() makes a new list. a does not change.

Make a free account to save your work and track your progress.

Built-in functions save work

Python has functions that save work. max() gives the biggest value. min() gives the smallest. len() counts. count() counts one value.

To find an average, add the values up. Then divide by how many there are.

Worked example: an average

StepScores 40, 60Scores 10, 20, 30
1 Add them up40 + 60 = 10010 + 20 + 30 = 60
2 Count them23
3 Divide the total by the count100 / 2 = 5060 / 3 = 20

The cells students fill in are left blank in this preview.

Your turn: the leaderboard

Build three tools for a leaderboard.

  1. best_score gives back the biggest score.
  2. count_passes counts the scores that are the pass mark or higher.
  3. average adds the scores up and divides by how many there are.

Press Run Tests to check.

Code: python
def best_score(scores):
    # Give back the biggest score.
    return None


def count_passes(scores, pass_mark):
    # Count the scores that are the pass mark or higher.
    return None


def average(scores):
    # Add up the scores and divide by how many there are.
    return None

Make a free account to save your work, or press Start lab to work through the whole lesson.

Match the mistake to its meaning

Have a go

Loading…

Your answers are marked here and are not kept. A college account keeps every student’s marks.

Your turn: fix four bugs

Four functions each have one bug. Find it and fix it.

  1. last_item should give back the last item.
  2. sorted_scores should give back the scores, lowest first.
  3. safe_price should give back 0 for an item that is not on the menu.
  4. first_item should give back the first item.

Press Run Tests and read each error message.

Code: python
def last_item(items):
    # Give back the last item in the list.
    return items[len(items)]


def sorted_scores(scores):
    # Give back the scores in order, lowest first.
    return scores.sort()


def safe_price(menu, item):
    # Give back the price. If the item is not on the menu, give back 0.
    return menu[item]


def first_item(items):
    # Give back the first item in the list.
    return items[1]

Make a free account to save your work, or press Start lab to work through the whole lesson.

Key words crossword

Have a go

Loading…

Your answers are marked here and are not kept. A college account keeps every student’s marks.

Exit quiz

Have a go

Exit quiz

6 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Remember

Important

The last index is len minus 1. sort() gives None. Check a key with in. Use max, min and len to save work.

Teach this lesson with your class

On a college account your students work the tasks and the labs as well, and every mark is kept for you.