python - Remove items from a list while iterating -
i'm iterating on list of tuples in python, , attempting remove them if meet criteria.
for tup in somelist: if determine(tup): code_to_remove_tup
what should use in place of code_to_remove_tup
? can't figure out how remove item in fashion.
you can use list comprehension create new list containing elements don't want remove:
somelist = [x x in somelist if not determine(x)]
or, assigning slice somelist[:]
, can mutate existing list contain items want:
somelist[:] = [x x in somelist if not determine(x)]
this approach useful if there other references somelist
need reflect changes.
instead of comprehension, use itertools
. in python 2:
from itertools import ifilterfalse somelist[:] = ifilterfalse(determine, somelist)
or in python 3:
from itertools import filterfalse somelist[:] = filterfalse(determine, somelist)
Comments
Post a Comment