Python - Removing Items from a List

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
                       
What should I use in place of code_to_remove_tup? A list comprehension is best for this kind of loop.

                       
                       somelist = [x for x in somelist if determine(x)]
                       
If I want to 'determine' what should be deleted. That would then be just.

                       
                       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))
                       

Leave a comment