When you iterate over a list, you should never remove elements! That will mess up your iteration. The only way to cleanly edit a list while iterating over it in Python is to iterate backwards over the length of the list and delete elements as you go.
For example this works as an efficient in-place deletion loop:
a = ['one two three', 'four five six', 'seven eight nine']
b = ['two', 'five six']
for i in range(len(a) - 1, -1, -1):
for x in b:
if x in a[i]:
del a[i]
print a # prints ['seven eight nine']
Furthermore, in your opening question, you said that you wanted to use comparison by words. your current loop does not do that. Consider that while you loop over the list b
, you actually try to see if the two-word string is a substring of some item in a
. You don't want to use the two-word string together. You want to split the string up into its separate word elements. For that, the split()
function is key.
Notice that the following code does NOT delete the second element in the list:
a = ['one two three', 'four six five', 'seven eight nine']
b = ['two', 'five six']
for i in range(len(a) - 1, -1, -1):
for x in b:
if x in a[i]:
del a[i]
print a # prints ['four six five', 'seven eight nine']
All I did was switch the order of 'six' and 'five' in a[1]
and your loop stopped working. That's because it was looking for the string 'five six' in the string 'four six five' and obviously couldn't find it because there were no exact matches for that particular string.
Now if we try to split
the string up into words, we can do actually do checks by iterating over the list of words.
a = ['one two three', 'four six five', 'seven eight nine']
b = ['two', 'five six']
for i in range(len(a) - 1, -1, -1):
for x in b:
for word in x.split():
if word in a[i]:
del a[i]
print a # correctly prints ['seven eight nine']