If I have a function matchCondition(x)
, how can I remove the first n
items in a Python list that match that condition?
One solution is to itera
The accepted answer was a little too magical for my liking. Here's one where the flow is hopefully a bit clearer to follow:
def matchCondition(x):
return x < 5
def my_gen(L, drop_condition, max_drops=3):
count = 0
iterator = iter(L)
for element in iterator:
if drop_condition(element):
count += 1
if count >= max_drops:
break
else:
yield element
yield from iterator
example = [1, 10, 2, 9, 3, 8, 4, 7]
print(list(my_gen(example, drop_condition=matchCondition)))
It's similar to logic in davidism answer, but instead of checking the drop count is exceeded on every step, we just short-circuit the rest of the loop.
Note: If you don't have yield from available, just replace it with another for loop over the remaining items in iterator
.