To fulfill these criteria: change the original list in place, there are no instances of the list, only one pass, it works , the traditional solution is to iterate backwards:
for i in xrange(len(somelist) - 1, -1, -1): element = somelist[i] do_action(element) if check(element): del somelist[i]
Bonus: does not execute len(somelist) at each iteration. Works on any version of Python (at least as far back as 1.5.2) ... s / xrange / range / for 3.X.
Update: if you want to iterate ahead, it's possible, just harder and uglier:
i = 0 n = len(somelist) while i < n: element = somelist[i] do_action(element) if check(element): del somelist[i] n = n - 1 else: i = i + 1
John Machin May 16 '11 at 23:30 2011-05-16 23:30
source share