
Side Quest: Keep the Quest Items
Pip wants to throw every rock out of the bag. This looks right, but it's a famous trap:
bag = ["rock", "rock", "gem", "rock"]
for item in bag:
if item == "rock":
bag.remove(item)
print(bag) # ['gem', 'rock'] a rock escaped!
What went wrong?
The loop walks through the list by position: 0, 1, 2… When an item is removed, everything after it slides one place to the left. Then the loop moves on to the next position, and jumps right over the item that slid into the gap.
Build a new list instead
Leave the original list alone. Loop over it, and append the items you want to keep to a new list:
kept = []
for item in bag:
if item != "rock":
kept.append(item)
print(kept) # ['gem']
Nothing shifts, so nothing gets skipped. And the original list is still there if you need it later.
Pip tip: "Don't change a list while you loop over it" is a good rule for every language, not just Python.
Assignment
Pip's bag is full of junk. Keep the quest items!
- Loop over
bag. Append every item that is not"rock"and not"stick"tokept. - Count the thrown-away items in
dropped. - Don't change
bagitself, and don't useremoveorpop.
Pip's bag is full of junk. Keep the quest items!
- Loop over
bag. Append every item that is not"rock"and not"stick"tokept. - Count the thrown-away items in
dropped. - Don't change
bagitself, and don't useremoveorpop.
Press Run to try your code, then Check to test it.