Today I am going to explain a small piece of code to remove items from a list.
Let's say
I'm iterating over a list of tuples in Python, and am attempting to remove them if they meet certain criteria.
for tup in somelist:
if determine(tup):
code_to_remove_tup
somelist = [x for x in somelist if determine(x)]
somelist = [x for x in somelist if not determine(x)]
EDIT: The above would create a new list and assign it the name of old list. So, you will loose reference to the original list unless you do it this way,This is explained in List slicing(One of my previous posts)
somelist[:] = [x for x in somelist if not determine(x)]
Also, using itertools(explained in a previous post). However there is no non iterator filterfalse, so it will have to be.
from itertools import ifilterfalse
somelist[:] = list(ifilterfalse(determine, somelist))
Written by Vivek Soundrapandi
Published Date: {{ article.pub_date }}
View all posts by: Vivek Soundrapandi