Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove items from a list that contains words found in items in another list [duplicate]

Tags:

python

list

I want to remove items from list 'a' where list 'b' contains items with words found in list 'a'

a = ['one two three', 'four five six', 'seven eight nine']
b = ['two', 'five six']

The result should be:

a = ['seven eight nine']

This because the words 'two' and 'five six' are found in items in list 'a'.

This is how I have tried to solve it:

for i in a:
    for x in b:
        if x in i:
            a.remove(i)

This returns:

print a
['four five six', 'seven eight nine']

Why does this not work, and how can I solve this problem?

Thanks.

like image 213
user2758396 Avatar asked Sep 13 '13 15:09

user2758396


People also ask

How do you remove an element from a list in another list?

To remove an element from a list using the remove() method, specify the value of that element and pass it as an argument to the method. remove() will search the list to find it and remove it.

How do you remove a particular item from within a list called mylist?

How do I remove a specific element from a list in Python? The remove() method removes the first matching element (which is passed as an argument) from the list. The pop() method removes an element at a given index, and will also return the removed item.


1 Answers

Lists should not be modified while they're being iterated over. Doing so can have undesirable side effects, such as the loop skipping over items.

Generally in Python you should avoid loops that add and remove elements from lists one at a time. Usually those kinds of loops can be replaced with more idiomatic list comprehensions.

[sa for sa in a if not any(sb in sa for sb in b)]

For what it's worth, one way to fix your loops as written would be to iterate over a copy of the list so the loop isn't affected by the changes to the original.

for i in a[:]:
    for x in b:
        if x in i:
            a.remove(i)
like image 50
John Kugelman Avatar answered Oct 03 '22 11:10

John Kugelman