how to remove multiple occurrences of a string within a list?

Steven Bethard steven.bethard at gmail.com
Wed Apr 4 17:49:23 EDT 2007


Ayaz Ahmed Khan wrote:
> "kyosohma" typed:
> 
>> If you want to get really fancy, you could do a list comprehension
>> too:
>>
>> your_list = ["0024","haha","0024"]
>> new_list = [i for i in your_list if i != '0024']
> 
> Or, just:
> 
> In [1]: l = ["0024","haha","0024"]
> In [2]: filter(lambda x: x != "0024", l)
> Out[2]: ['haha']

Only if you want to make your code harder to read and slower::

     $ python -m timeit -s "L = ['0024', 'haha', '0024']"
     "[i for i in L if i != '0024']"
     1000000 loops, best of 3: 0.679 usec per loop

     $ python -m timeit -s "L = ['0024', 'haha', '0024']"
     "filter(lambda i: i != '1024', L)"
     1000000 loops, best of 3: 1.38 usec per loop

There really isn't much use for filter() anymore.  Even in the one place 
I would have expected it to be faster, it's slower::

     $ python -m timeit -s "L = ['', 'a', '', 'b']" "filter(None, L)"
     1000000 loops, best of 3: 0.789 usec per loop

     $ python -m timeit -s "L = ['', 'a', '', 'b']" "[i for i in L if i]"
     1000000 loops, best of 3: 0.739 usec per loop

STeVe



More information about the Python-list mailing list