1

I'm trying to remove spam from the given choices on the menu, my for loop doesn't work.

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 choice in menu:
    if "spam" in choice:
        remove("spam")
        print(choice)
martineau
  • 112,593
  • 23
  • 157
  • 280
Caden Hale
  • 11
  • 1

3 Answers3

7

As stated by @h4z4, remove is not defined. Try

for choice in menu:
    if "spam" in choice:
        choice.remove("spam")
        print(choice)

However, remove only removes the first occurrence. To remove all occurrences, try:

for choice in menu:
    if "spam" in choice:
        choice = [item for item in choice if item != "spam"]
        print(choice)
Kraigolas
  • 3,728
  • 3
  • 8
  • 27
5

To remove all "spam" from sublists, use list-comprehension:

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"],
]

menu = [[val for val in subl if val != "spam"] for subl in menu]
print(menu)

Prints:

[['egg', 'bacon'], 
 ['egg', 'sausage', 'bacon'], 
 ['egg'], 
 ['egg', 'bacon'], 
 ['egg', 'bacon', 'sausage'], 
 ['bacon', 'sausage'], 
 ['sausage', 'bacon', 'tomato'], 
 ['egg', 'bacon']]
Andrej Kesely
  • 118,151
  • 13
  • 38
  • 75
0
  1. As already pointed out remove is a method of list and should be called as choice.remove("spam")
  2. remove only removes the first occurrence of the element

Here is a way to do this with remove and count

Code:

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 choice in menu:
    c = choice.count('spam') # returns number of occurrences of 'spam' in choice
    while c: # to remove spam from choice c times
        choice.remove("spam")
        c-=1

print(*menu, sep='\n')

Output:

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

But I would prefer list comprehension

Abhi_J
  • 1,946
  • 1
  • 3
  • 16