a bug in list.remove?

Astan Chee stanc at al.com.au
Fri Aug 18 15:17:07 EDT 2006



Tim Chase wrote:

>> I have 2 lists. What Im doing is check the first list and remove all 
>> occurances of the elements in the second list from the first list, 
>> like so:
>>  >>> ps = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
>>  >>> qs = [6,7,8,9,10,11,12,1,2]
>>  >>> for p in ps:
>>     if p in qs:
>>         ps.remove(p)
>>
>> The problem Im having is that when I do
>>  >>> print ps
>>  it gives me
>> [2, 3, 4, 5, 7, 9, 11, 13, 14, 15]
>> which is incorrect since 2,7,9,11 shouldnt be in that list. Is this a 
>> bug in .remove? or is my algorithm somewhat flawed?
>
>
>
> I'd go with the "somewhat flawed" answer.
>
> I'd just use
>
> ps = [x for x in ps if x not in qs]
>
> which will remove *all* instances of x from ps if it exists in qs.  
> There's a subtle difference from the remove() method, which will only 
> remove the first instance:
>
> >>> help([].remove)
> Help on built-in function remove:
>
> remove(...)
>     L.remove(value) -- remove first occurrence of value
>
>
>
> If qs is large, you'll get improved performance by converting it to a 
> set first:
>
> >>> s = set(qs)
> >>> ps = [x for x in ps if x not in s]
>
>
> As for your algorithm, you're modifying the list over which you're 
> iterating--at best, often considered bad form...at worst, I've had 
> Python throw exceptions at me for attempting it.
>
> -tkc

Thanks for that. Really helpful!
Cheers
Astan



More information about the Python-list mailing list