When you delete an item from a list at a specific index, all the items after the specified index get moved forward by 1 since there can be no gap in a list, so after you delete the 2
at index 1
, for example, in the next iteration x
would become 2
at the index 2
when it used to be at index 3
, so your own index
variable would be pointing to the wrong item.
To delete items from a list in-place, you should instead count backwards from the end of the list so that the re-indexing of the list after you delete an item won't affect the accuracy of your index
counter:
def keep(the_list, target):
index = len(the_list) - 1
while index >= 0:
if the_list[index] != target:
del the_list[index]
index -= 1
so that:
the_list = [1, 2, 1, 2, 3, 1, 2, 3, 4]
target = 1
keep(the_list, target)
print(the_list)
would output:
[1, 1, 1]
But keep in mind that deleting an item from a list is inherently inefficient since it has an average time complexity of O(n) for having to move items after the given index, so deleting multiple items from a list becomes quadratic in complexity. It's much more efficient to use list comprehension to construct a new list from the old one by retaining only items that are equal to the target value. So even though the code above shows you how to correctly delete items from a list in-place, you should not actually use it in any production code.