"Canonical" way of deleting elements from lists

Fredrik Lundh fredrik at pythonware.com
Wed Jan 9 05:12:31 EST 2008


Robert Latest wrote:
>>From a list of strings I want to delete all empty ones. This works:
> 
>     while '' in keywords: keywords.remove('')
> 
> However, to a long-term C programmer this looks like an awkward way of 
> accomplishing a simple goal, because the list will have to be re-evaluated 
> in each iteration.

you're using a quadratic algorihm ("in" is a linear search, and remove 
has to move everything around for each call), and you're worried about
the time it takes Python to fetch a variable?

 > Is there a way to just walk the list once and throw out unwanted
 > elements as one goes along?

creating a new list is always almost the right way to do things like 
this.  in this specific case, filter() or list comprehensions are good 
choices:

    keywords = filter(None, keywords) # get "true" items only

    keywords = [k for k in keywords if k]

also see:

    http://effbot.org/zone/python-list.htm#modifying

</F>




More information about the Python-list mailing list