Delete all items in the list
Gabriel Genellina
gagsl-py2 at yahoo.com.ar
Thu Feb 26 10:26:56 EST 2009
En Thu, 26 Feb 2009 11:00:30 -0200, Boris Borcic <bborcic at gmail.com>
escribió:
> Chris Rebert wrote:
>> On Thu, Feb 26, 2009 at 3:05 AM, Clarendon <jineu21 at hotmail.com> wrote:
> ...
>>> L=['a', 'b', 'c', 'a']
>>>
>>> I want to delete all 'a's from the list.
>>> But if L.remove('a') only deletes the first 'a'.
>>>
>>> How do you delete all 'a's?
>> There are several ways. I'd go with a list comprehension:
>
> and for a couple other ways
>
> while 'a' in L : L.remove('a')
This is probably the worst way, takes cuadratic time (and two searches per
loop).
> L = filter('a'.__ne__,L)
And this is probably the fastest. But not all types define __ne__ so a
more generic answer would be:
from functools import partial
from operator import ne
L = filter(partial(ne, 'a'), L)
Of course, this is only relevant if L is large and there are many
duplicates. In other cases I'd stick with the list comprehension as posted
by Chris Rebert.
--
Gabriel Genellina
More information about the Python-list
mailing list