deleting multiple elements without updating till the end
list, python
Solution
Two options:
Create a new list with a list comprehension:
newlist = [el for i, el in enumerate(oldlist) if i not in indices_to_delete]
This will be all the faster if `indices_to_delete` was a `set`:
indices_to_delete = set(indices_to_delete)
newlist = [el for i, el in enumerate(oldlist) if i not in indices_to_delete]
because membership testing in a set is O(1) vs. O(n) in a list.
Remove the indices in reverse-sorted order from the list in-place:
for index in sorted(indices_to_delete, reversed=True):
del oldlist[index]
If you don't remove items in reverse sorted order, items with higher indices are moved up as items with lower indices are removed and the rest of your `indices_to_delete` no longer match the items you needed to remove.
Problem
I have two lists: ``` list_a = [1,5,8] list_b = [12,4,2,5,7,5,3,6,8] ``` The elements in `list_a` correspond to the indices of elements in `list_b`. Both lists are of size greater than 100. How can I delete the elements of `list_b` whose indices are in `list_a`, so if you take the lists above the resulting list is `[12,2,5,7,3,6]`?