0

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?

dylnmc
  • 3,810
  • 4
  • 26
  • 42
  • possible duplicate of [Deleting multiple elements from a list](http://stackoverflow.com/questions/497426/deleting-multiple-elements-from-a-list) – jonrsharpe Sep 22 '14 at 15:35

1 Answers1

1

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]
falsetru
  • 357,413
  • 63
  • 732
  • 636
  • I didn't know about reversed. However, you also forgot to order indexes – dylnmc Sep 22 '14 at 15:28
  • Also, this was what I was afraid I would have to do; is there anything else that is neater? – dylnmc Sep 22 '14 at 15:29
  • Smartest answer to this problem provided by @falsetru. You basically sort your indexes by descending order, so you won't have to worry about the list getting adjusted after each deletion. –  Sep 22 '14 at 15:30
  • Interestingl I didn't think of that... the enumerate .. if not in indexes. – dylnmc Sep 22 '14 at 15:30
  • Umm... question: why does `a = [1,2,3,4,5,6]\ for ind, num in enumerate(a): print a.pop(ind)` work? I thought it would, but it actually does. Does python make the list `a` temporarily "locked" such that removing an index while in a for loop doesn't shift them all down? – dylnmc Sep 22 '14 at 19:22
  • @Miche (a)Someone... new part of the question... see update or above comment. Why? – dylnmc Sep 22 '14 at 19:26
  • list.pop(index) removes the element but doesn't affect the keys, hence in your example, it does work, but it could give you some weird behavior in another context since you don't really see if you are still within the bounds of your list. –  Sep 22 '14 at 20:04