Simeon Aleksov - 1 year ago 113
Python Question

# Keeping the same enumerator while deleting elements from a list python

So, I am trying to delete items from my list while enumerating, however whenever I delete an item, the enumerator resets, is there any way to keep it same as the original before deleting anything?

`y`
- is a list with numbers(aka indexes I want to be deleted in my original list)
For example, if I have this list

``````lst = [(0,1),(1,1)(2,2)]
``````

and if I do
`del lst[1]`
, it will become
`[(0,1,(1,2)]`
right? However I want it to become
`[(0,1)(2,2)]`
. Is there a way to do that?

``````lst = [99,14,16,61,87,41]
y = [5,1,3,0]

for q,w in enumerate(lst):
for e in y:
if q == e:
del lst[q]
``````

Actual output =
`[14, 61, 87]`
, Desired output =
`[16,87]`

If you want to use `enumerate()` you can do it within a list comprehension. This creates a new list without the items with indices in `y` (which I have converted to a set to remove duplicates and improve performance):

``````lst = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
y = set([1, 5, 8, 2])
lst[:] = [item for i,item in enumerate(lst) if i not in y]

>>> lst
[0, 3, 4, 6, 7, 9]
``````

Another way is to delete the items from the back of the list:

``````lst = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
y = [1, 5, 8, 2, 1, 2, 5]
for i in sorted(set(y), reverse=True):
del lst[i]

>>> lst
[0, 3, 4, 6, 7, 9]
``````

Here `y` is first converted to a set to remove any possible duplicate indices, then sorted in reverse. Then the items from the list can be safely removed.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download