hymloth and sven respond to work, but they do not change the list (create a new one). If you need to modify the object, you need to assign a slice:
x[:] = [value for value in x if len(value)==2]
However, for large lists in which you need to remove multiple items, this is memory consumed, but it works in O (n).
glglgl answer suffers from O (n²) complexity because list.remove is O (n).
Depending on the structure of your data, you may prefer to mark the indices of the elements to be deleted and use del to delete by index:
to_remove = [i for i, val in enumerate(x) if len(val)==2] for index in reversed(to_remove):
Now del x[i] also O (n), because you need to copy all the elements after index i (the list is a vector), so you will need to test this against your data. However, this should be faster than using remove , because you do not pay the cost of the search phase for removal, and the cost of copying is the same in both cases.
[edit] A very good version in place, O (n) with limited memory requirements, courtesy of @Sven Marnach . It uses itertools.compress , which was introduced in python 2.7:
from itertools import compress selectors = (len(s) == 2 for s in x) for i, s in enumerate(compress(x, selectors)):
gurney alex Nov 29 '11 at 3:11 a.m. 2011-11-29 15:11
source share