I wrote a function that takes 2 lists and removes the elements that show up in both but sometimes they don't remove them.
def function(l1, l2):
for w1 in l1 :
for w2 in l2 :
if w1 == w2 :
l1.remove(w1)
l2.remove(w2)
return l1, l2
By debugging the script, I found out that upon finding and removing a common word, it skips the word next to the one that has been removed for both lists.
['a', 'b', 'c', 'd', 'e'] -> ['a', 'c', 'd', 'e'] instead of ['a', 'c', 'd', 'e']
I'm clueless on what I can do to fix this bug, for all I know it could be painfully obvious.
CodePudding user response:
You can use the copy of the list instead of using main list like this-
def function(l1, l2):
for w1 in l1[:]: # iterate over a copy of l1
if w1 in l2: # check if w1 is in l2
l1.remove(w1)
l2.remove(w1)
l1 = ['a', 'b', 'c', 'd', 'e']
l2 = ['l', 'b', 'm', 'o', 'e']
print(function(l1, l2))
print(l1, l2)
Another way,
def function(l1, l2):
return [w for w in l1 if w not in l2], [w for w in l2 if w not in l1]
l1 = ['a', 'b', 'c', 'd', 'e']
l2 = ['l', 'b', 'm', 'o', 'e']
print(function(l1, l2))
Output:
['a', 'c', 'd'] ['l', 'm', 'o']
Explanation: when you remove an element from a list, it changes the length of the list, which means that the for loop will not iterate through all the elements. This can cause the function to not remove all the common elements in the lists. So you can use either copy the first list and then compare(1st approach) or use separate filtering with list comprehension(2nd approach)