Caden Hale
Caden Hale

Reputation: 11

How to remove specific item from list?

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)

Upvotes: 1

Views: 312

Answers (3)

Abhi_J
Abhi_J

Reputation: 2129

  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

Upvotes: 0

Andrej Kesely
Andrej Kesely

Reputation: 195438

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']]

Upvotes: 5

Kraigolas
Kraigolas

Reputation: 5560

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)

Upvotes: 7

Related Questions