I am trying to figure out what is the best way to delete list items (fruits) when they match items from another list (test).
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
test = ["nana", "erry"]
newList = ["apple", "banana", "cherry", "kiwi", "mango"]
for x in test:
for y in fruits:
if x in y:
newList.remove(y)
print(newList)
Output from newList is as expected: ['apple', 'kiwi', 'mango']
If I try to solve this with a list comprehension the items will be removed but the list is printed twice as of the for loop.
fruitsNew = [y for x in test for y in fruits if x not in y]
print(fruitsNew)
Output from fruitsNew is: ['apple', 'cherry', 'kiwi', 'mango', 'apple', 'banana', 'kiwi', 'mango']
In the first iteration items which match "nana" is removed and in the second iteration words with "erry" are removed. Is there a way to print the list just once while removing the matched items? Or is list comprehension for this problem not applicable?
regards