"Canonical" way of deleting elements from lists
Hrvoje Niksic
hniksic at xemacs.org
Wed Jan 9 05:29:12 EST 2008
Robert Latest <boblatest at yahoo.com> writes:
> From a list of strings I want to delete all empty ones. This works:
>
> while '' in keywords: keywords.remove('')
If you're looking for a quick (no quadratic behavior) and convenient
way to do it, you can do it like this:
keywords = [s for s in keywords if s != '']
But that creates a new list, which might not be wanted for long lists
with few empty elements (or for shared lists). It also iterates over
every list element in a Python loop, which can take some time for long
lists.
> Is there a way to just walk the list once and throw out unwanted
> elements as one goes along?
I'd do it like this:
i = 0
while 1:
try:
i = keywords.index('', i)
except ValueError:
break
del keywords[i]
Or even:
try:
i = 0
while 1:
i = keywords.index('', i) # throws ValueError and stops the loop
del keywords[i]
except ValueError:
pass
In both cases the search for the empty string is done in efficient C
code, and you only loop in Python over the actual matches.
More information about the Python-list
mailing list