I want a function that removes values from a list if a predicate evaluates to True. The best I could come up with is:<br><br>def extract(lst, pred):<br> idx = 0<br> ret = []<br> for obj in lst[:]:<br> if pred(obj):<br>
ret.append(obj)<br> lst.pop(idx)<br> else:<br> idx += 1<br> return ret<br><br>Anybody have a better, more Pythonic solution? One of my failed attempts was this code, which fails when the predicate itself has "state":<br>
<br>def extract(lst, pred):<br> # BAD: Would not work in a case like pred = "extract every other object"<br> ret = filter(lst, pred)<br> for obj in ret: <br> lst.remove(obj)<br> return ret<br>