What is the most efficient way to do this?
Skip Montanaro
skip at pobox.com
Fri Feb 8 15:13:37 EST 2002
mdk> What is the most efficient way to remove empty items from this
mdk> list?
mdk> ['', '1', '2', '3', '', '456', '789', 'wow']
I'll give you a couple options and let you worry about efficiency...
>>> l = ['', '1', '2', '3', '', '456', '789', 'wow']
>>> filter(None, l)
['1', '2', '3', '456', '789', 'wow']
>>> [x for x in l if x != '']
['1', '2', '3', '456', '789', 'wow']
>>> while '' in l:
... l.remove('')
...
>>> l
['1', '2', '3', '456', '789', 'wow']
Note that the first two ways create new lists and leave l untouched. The
third way modifies l in place.
--
Skip Montanaro (skip at pobox.com - http://www.mojam.com/)
More information about the Python-list
mailing list