I try to delete items from a list based on the items in another list (in a loop). Error: Out-of-range list index


This is my code:

print('oc before remove',oc)
print('remlist before remove', remlist)

for i in range(len(remlist)):
    for j in range(len(oc)):
        if ( (remlist[i][0] == oc[j][0]) and (remlist[i][1] == oc[j][1]) ):
            del oc[j]

print('oc after remove', oc)

'oc' is de list from which I want to remove items that also occur in 'remlist'. My prints output the following:

('oc before remove', [[0, 0, 0]])
('remlist before remove', [[0, 0, 0]])
('oc after remove', [])
('oc before remove', [[1, 0, 1], [0, 1, 1]])
('remlist before remove', [[0, 0, 0], [1, 0, 1]])

Here the error occurs.

So the first time it succeeds, but the second time the following error is given:

IndexError: list index out of range

I understand the meaning of this error, but I don't see why this error occurs here. I use the length of both lists to loop. What is going wrong here?

Your problem is that you change the size of the list during iteration. Which obviously is a problem since after deleting a few items your j loop variable is going to be outside the range of the new (after deletion) list length. The first time it only works because the list only contains 1 element.

Try this instead:

oc = [item for item in oc if item not in remlist]

This list comprehension will keep the items from oc that are not in remlist.