sdoubleu
sdoubleu

Reputation: 13

List comprehension applicable for removing matching items from another list?

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

Upvotes: 1

Views: 125

Answers (2)

Keith
Keith

Reputation: 43054

Here you have duplicated the source list and removed elements from the duplicate. That would be inefficient. Why not just build up the new list according to the criteria? That's what list comprehensions are for.

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
test = ["nana", "erry"]

newlist = [name for name in fruits if all(t not in name for t in test)]

assert newlist == ['apple', 'kiwi', 'mango']

In other words, try to avoid list comprehensions with side effects. Here, removal of elements from a different list is a side effect. If you really need that, just use the for loop form.

Upvotes: 0

python_user
python_user

Reputation: 7123

You can use any for this.

fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
test = ["nana", "erry"]
newList = ["apple", "banana", "cherry", "kiwi", "mango"]

res = [i for i in fruits if not any(j in i for j in test)]

print(res)

Output

['apple', 'kiwi', 'mango']

Upvotes: 1

Related Questions