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

Thomas Nelson thn at mail.utexas.edu
Tue Apr 3 14:56:48 EDT 2007


On Apr 3, 1:49 pm, kyoso... at gmail.com wrote:
> On Apr 3, 1:31 pm, "Matimus" <mccre... at gmail.com> wrote:
>
> > It depends on your application, but a 'set' might really be what you
> > want, as opposed to a list.
>
> > >>> s = set(["0024","haha","0024"])
> > >>> s
>
> > set(["0024","haha"])>>> s.remove("0024")
> > >>> s
>
> > set(["haha"])
>
> If you want, you can also loop over the list, like so:
>
> counter = 0
> your_list = ["0024","haha","0024"]
> for i in your_list:
>         if i == '0024':
>                 your_list.pop(counter)
>         counter += 1
>
> Mike

This method doesn't work.
>>> li = list('hello larry')
>>> count = 0
>>> for i in li:
...     if i=='l':
...             li.pop(count)
...     coun += 1
...
'l'
'l'
>>> l
['h', 'e', 'l', 'o', ' ', 'a', 'r', 'r', 'y']

because the indexes change as you pop, it gets some of them but not
all.




More information about the Python-list mailing list