I want to remove all elements from a list I want to iterate over a list, skipping elements that match some test, and a certain number of elements after that match. eg.
# skip 'foo' and 2 subsequent values
values = [1, 2, 3, 'foo', 'a', 'b', 6, 7, 'foo', 'x', 'y']
result = [1, 2, 3, 6, 7]
Is there a more elegant method to achieve this than iterating using a counter building a new list and skipping forwards n iteratations when the match is found? ie.
values = [1, 2, 3, 'foo', 'a', 'b', 6, 7, 'foo', 'x', 'y']
result = []
i = 0
while i < len(values):
if values[i] == 'foo':
i += 3
else:
result.append(values[i])
i += 1
print result
[1, 2, 3, 6, 7]
Hmm, how about a generator?