iterating through lists to delete elements

Bjorn Pettersen BPettersen at NAREX.com
Thu Aug 9 12:13:54 EDT 2001


> From: Mark Robinson [mailto:m.1.robinson at herts.ac.uk]
> 
> Can anyone advise me the best way to iterate through a list 
> and deleting 
> elements that don't meet a certain criteria.

You can use either filter or list comprehensions:

>>> x = [1,2,3,4,5,6,7,8,9]
>>> print filter.__doc__
filter(function, sequence) -> list

Return a list containing those items of sequence for which
function(item)
is true.  If function is None, return a list of items that are true.
>>> filter(lambda x: x > 5, x)
[6, 7, 8, 9]
>>> [ item for item in x if item > 5 ]
[6, 7, 8, 9]
>>>

hth,
-- bjorn




More information about the Python-list mailing list