0

On Udemy there was this challenge where you have to remove a specific string from the list. In this challenge, it was "spam". So here was the given List:

[
    ["egg", "bacon"],
    ["egg", "sausage", "bacon"],
    ["egg", "spam"],
    ["egg", "bacon", "spam"],
    ["egg", "bacon", "sausage", "spam"],
    ["spam", "bacon", "sausage", "spam"],
    ["spam", "sausage", "spam", "bacon", "spam", "tomato", "spam"],
    ["spam", "egg", "spam", "spam", "bacon", "spam"],
]

Below is the solution proposed by me:

menu = [
    ["egg", "bacon"],
    ["egg", "sausage", "bacon"],
    ["egg", "spam"],
    ["egg", "bacon", "spam"],
    ["egg", "bacon", "sausage", "spam"],
    ["spam", "bacon", "sausage", "spam"],
    ["spam", "sausage", "spam", "bacon", "spam", "tomato", "spam"],
    ["spam", "egg", "spam", "spam", "bacon", "spam"],
]
for meal in menu:
    for item in meal:
        if "spam" in item:
            meal.remove("spam")
    print(meal)

After the code is executed all "spam" is removed except the last one. I tried debugging and the removal of the last spam does get executed but not sure why it still shows in the output. Below is the output:

['egg', 'bacon']

['egg', 'sausage', 'bacon']

['egg']

['egg', 'bacon']

['egg', 'bacon', 'sausage']

['bacon', 'sausage']

['sausage', 'bacon', 'tomato']

['egg', 'bacon', '**spam**']

Can someone please help me to find the error? Or is this a bug?

1 Answers1

4

Use a list comprehension to avoid the problem of removing an item from a list that you are iterating over, as well as for cleaner code.

spam_free = [[item for item in meal if item != "spam"] for meal in menu]

If you want to do it the old-fashioned wy as in your example, just be sure to create new lists:

spam_free = []
for meal in menu:
    new_meal = []
    spam_free.append(new_meal)
    for item in meal:
        if item != "spam":
            new_meal.append(item)
Joshua Fox
  • 18,704
  • 23
  • 87
  • 147