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.
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 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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With