iterating through lists to delete elements
skip at pobox.com
Thu Aug 9 22:30:45 CEST 2001
Joseph> Bjorn Pettersen wrote:
>> > 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:
Joseph> So it seems that (shudder) There's More Than One Way To Do
Joseph> It. Isn't there supposed to be one (obvious) way?
Well, list comprehensions are generally a cleaner way than using map, filter
and/or lambda to massage one list into another.
Actually, neither the filter nor the list comprehension solutions posted
meet the original posters requirements that you iterate through the list and
delete elements not meeting certain criteria. If the list has thousands of
elements, creating a new list may not be a wise choice.
Skip Montanaro (skip at pobox.com)
More information about the Python-list