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

Steven D'Aprano steve at REMOVEME.cybersource.com.au
Wed Apr 4 05:08:04 EDT 2007


On Wed, 04 Apr 2007 00:59:23 -0700, 7stud wrote:

> On Apr 3, 3:53 pm, "bahoo" <b83503... at yahoo.com> wrote:
>> > target = "0024"
>> > l = ["0024", "haha", "0024"]
>>
>>
>> > for index, val in enumerate(l):
>> >     if val==target:
>> >         del l[index]
>>
>> > print l
>>
>> This latter suggestion (with the for loop) seems to be buggy: if there
>> are multiple items in the list "l" equal to "target", then only the
>> first one will be removed!
>>
>> Thanks anyways.
> 
> Prove it.

Try replacing l = ["0024", "haha", "0024"]
with 

l = ["0024", "0024", "haha"]

and re-running the code.


Actually, the description of the bug isn't quite right. The behaviour of
the for loop isn't defined -- sometimes it will work, sometimes it won't,
depending on how many items there are, and which of them are equal to the
target.

The reason it is buggy is that it is deleting items from the same list it
is trying to enumerate over. The only safe way to do that is to iterate
over the list backwards, only deleting items you've already seen and won't
go over again:

for i in range(len(my_list), -1, -1)):
    if condition:
        del my_list[i]


I don't think reversed() will help you here, but I can't check for sure
because I've only got Python 2.3 on this system.


-- 
Steven D'Aprano 





More information about the Python-list mailing list