A lesson learnt in debugging a Python list.
Guess what will be the output.
inbox = [ "spam", "spam", "boss" ]
for msg in inbox:
if msg == "spam":
inbox.remove(msg)
print(inbox)['spam', 'boss']Reason#
Ever wonder why there is still one spam in the list? Here is why.
When we remove() an item from a Python list,
the list will slice on to the next item.
In this case, when it remove() the first “spam”,
The list pointer will slice to the next, which is the “boss”.
Solution#
Build a new list with append().
inbox = [ "spam", "spam", "boss" ]
keep = []
for msg in inbox:
if msg != "spam":
keep.append(msg)
print(keep)['boss']

