1

I need to delete elements from a list whilst iterating over it (I cannot create a new list as it is referenced in code I have no control over).

The best I've come up with is:

last_index = len(somelist) - 1
for (index,item) in enumerate(reversed(somelist)):
    if somecondition(item):
        del somelist[last_index - index]

Are there better alternatives? I've seen this post and this one too, but none of the solutions provided are as efficient or as concise (IMHO).

Community
  • 1
  • 1
isedev
  • 18,848
  • 3
  • 60
  • 59
  • How much more concise and efficient would you like? [Alex Martelli's answer](http://stackoverflow.com/a/1208792/78845) appears to be both. Questions relating to opinions are not a good match for Stack Overflow. – johnsyweb Feb 07 '13 at 16:14
  • Are you sure your code actually works? initializing `somelist` to `range(100)` and `somecondition(item)` to `item % 2`, I end up with an IndexError. – mgilson Feb 07 '13 at 16:17
  • @mgilson my first thought was that it should be `del somelist[-index]` (with `enumerate(...,start=1)`) otherwise, all ways I can think of are already covered by the previous post – Jon Clements Feb 07 '13 at 16:23
  • @isedev i'm not sure regarding to efficiency but also you can do somelist.remove(item) instead of reversing and enumerating. – tony Feb 07 '13 at 16:26
  • 1
    @JonClements -- It's a shame this is a dupe -- I might have eventually gotten a `great answer` badge for it :O) – mgilson Feb 07 '13 at 16:29
  • sorry, cut'n'paste error in above code. Edited now. – isedev Feb 07 '13 at 16:31
  • @Johnsyweb -- having a bad day, hadn't seen the question with the answer you were referring to (there's another with nearly same title - [here](http://stackoverflow.com/questions/6022764/python-removing-list-element-while-iterating-over-list)). Indeed, Alex's answer is what I was after. – isedev Feb 07 '13 at 16:38

1 Answers1

2

You can use a list comprehension + slice assignment, which is certainly more concise -- I don't know about efficiency (although I would expect it to do better in that regard as well since you don't need to keep shifting elements in the list over every time you delete an item ...)

somelist[:] = [ x for x in somelist if not somecondition(x) ]
mgilson
  • 300,191
  • 65
  • 633
  • 696