Deleting multiple indexes from a list at once - python
You can remove them with a list comprehension, which will create a new list:
>>> lst = [2, 5, 7, 12, 13]
>>> [v for i, v in enumerate(lst) if i not in {4,3}]
[2, 5, 7]
You just have to assign this new list to lst
again.
You can use a list comprehension to rebuild the list:
indices = {3, 4}
newlist = [v for i, v in enumerate(oldlist) if i not in indices]
I used a set for the indices here, as set membership testing is faster than with a list.
Note that a delete (best done with del lst[index]
) partially rebuilds the list as well; doing so with one loop in a list comprehension can be more efficient.
Demo:
>>> oldlist = [2, 5, 7, 12, 13]
>>> indices = {3, 4}
>>> [v for i, v in enumerate(oldlist) if i not in indices]
[2, 5, 7]