Back

Debug Challenge: Lists

Difficulty  

divider

Objective

Four broken list programs. Two crash, two do not — and the two that do not are the ones worth worrying about.

Nearly every list bug comes down to the same question: which index are you actually on? Keep that in mind and all four become findable.

Skills to Practice

  • Indexing without running off either end
  • Knowing what len() gives you and what it does not
  • Deciding what belongs inside the loop and what belongs before it
  • Handling a value that is not in the list

The Four Programs

For each one: which kind of mistake, what is wrong, and the corrected line.


Bug 1

Symptom: crashes with an IndexError: list index out of range.

Bug 1
items = ["sword", "shield", "potion"]
print("Your last item is:", items[len(items)])

The list has three items. Write out what index each one lives at, then work out what len(items) gives you and why that is one too far.


Bug 2

Symptom: prints Total: 50. The three scores add up to 60.

Bug 2
scores = [10, 20, 30]
total = 0
for i in range(1, len(scores)):
total = total + scores[i]
print("Total:", total)

No crash this time, just a quietly wrong total. Which score got left out, and why? Note that this is the opposite mistake to Bug 1 — here the loop stops in the right place but starts in the wrong one.


Bug 3

Symptom: prints Roster: ['Cal']. All three players should be on the roster.

Bug 3
players = ["Ana", "Ben", "Cal"]
for name in players:
roster = []
roster.append(name)
print("Roster:", roster)

Only the last name survived. If you did the Loops debug challenge, you have met this bug before wearing a different costume — say what the two have in common.


Bug 4

Symptom: type mint and it correctly prints position 1. Type rocky road and it crashes with a ValueError.

Bug 4
flavors = ["vanilla", "mint", "coffee"]
wanted = input("Which flavor? ")
print("Found at position:", flavors.index(wanted))

The code is written correctly. The bug is that it assumes the flavor is on the list. You learned the tool for checking that in Activity 1.22 — use it.


Submit

  • Which kind of mistake each one is
  • One sentence on what was wrong
  • The corrected line

Then this: Bugs 1 and 2 are both off-by-one errors, but only one of them crashed. Which is more dangerous, and why?

Commence Debugging