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.
len() gives you and what it does notFor each one: which kind of mistake, what is wrong, and the corrected line.
Symptom: crashes with an IndexError: list index out of range.
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.
Symptom: prints Total: 50. The three scores add up to 60.
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.
Symptom: prints Roster: ['Cal']. All three players should be on the roster.
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.
Symptom: type mint and it correctly prints position 1. Type rocky road and it crashes with a ValueError.
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.
Then this: Bugs 1 and 2 are both off-by-one errors, but only one of them crashed. Which is more dangerous, and why?