I'm trying to iterate over a list and wanting print out every item except - spam. But, I keep getting an error stating the following: Expected type 'list[str]' (matched generic type '_T) got 'str' instead.
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"],
]
item = "-"
while item in menu != "spam":
continue
if "spam" in menu:
menu.remove("spam")
print(menu)`
I also tried the following:
if item in menu == "spam"
menu.remove("spam")
which results in the same issue.Can anyone help me with this? It's driving me insane.
CodePudding user response:
for items in menu:
for i in items:
if i!='spam':
print(i)
CodePudding user response:
Zanmato's solution is very simple and probably the best for this situation. However, it also changes the original list, which is probably desirable for this particular situation, but if you want to preserve the original list, you can use a list comprehension syntax like this to clean and print the list directly without having to create or overwrite another variable.
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"],
]
print([[item for item in submenu if item != "spam"] for submenu in menu])