Reputation: 4010
I'm facing a somewhat troubling problem: I have a list (for example (2, 5, 7, 3, 8)
) and I need to remove a couple of those but not all. Let's say I need to remove indexes 1
, 3
and 4
and I want to do that in a loop. Is there anyway (in Python or logically) to remove those indexes easily in a loop.
If I have a list remIndexes = (1, 3, 4)
, as soon as I remove index 1
, everything moves down one, so now I have (2, 7, 3, 8)
and the indexes for the numbers I wanted to remove are shifted down by one.
Does python provide a neat way of doing this or am I going to have to order the list remIndexes
and then go backwards through the list?
Note: remIndexes should be in order, but it could potentially not be in order. Ordering it isn't very hard, however.
UPDATE:
Why does
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
for ind, num in enumerate(lst):
print lst.pop(ind)
actually work????? (It prints 2 4 6 8 0
each on a newline.)
Does python freeze a list while you are in a for loop?
Upvotes: 0
Views: 376
Reputation: 369054
Iterate the reversed indexes:
>>> lst = [2, 5, 7, 3, 8]
>>> indexes = 1, 3, 4
>>> for i in reversed(indexes):
... del lst[i]
...
>>> lst
[2, 7]
Or use sorted(indexes, reverse=True)
if the indexes is not sorted.
Using list comprehension with enumerate
:
>>> lst = [2, 5, 7, 3, 8]
>>> indexes = 1, 3, 4
>>> indexes = set(indexes) # `x in set` is faster than `x in tuple/list`
>>> [x for i, x in enumerate(lst) if i not in indexes]
[2, 7]
Upvotes: 1