Problem with list.remove() method

Terry Reedy tjreedy at udel.edu
Tue Nov 20 15:32:21 EST 2012


On 11/20/2012 9:14 AM, Chris Angelico wrote:
> On Wed, Nov 21, 2012 at 12:56 AM, Alvaro Combo <alvaro.combo at gmail.com> wrote:
>> Hi All,
>>
>> I'm relatively new to Python... but I have found something I cannot explain... and  I'm sure you can help me.
>>
>> I have the following function that serves for removing the duplicates from a list... It's a simple and (almost) trivial task.
>>
>> I'm using WingIDE as editor/debugger and have Python 2.7.3.
>>
>> When running this I have an error when trying to remove cpy_lst[4]... and ONLY THAT!!! Even in interactive mode!!!
>
> Several points here. You've written a beautiful O(N^2) duplicates
> remover... Python has a really fast way of doing it, if you don't mind
> losing order:
>
> cpy_lst = list(set(lst))
>
> But let's assume you're doing this for the exercise. Your technique is
> fine, if inefficient on large lists, but the remove() method looks for
> the first occurrence of an element by its value - what you want is:
>
> del cpy_lst[i]
>
> which will remove one element by index.
>
> With that change, you'll have a slightly odd duplicate remover that
> keeps the *last* of any given element. That's rather unusual. Instead,
> you may want to consider maintaining a set of "items I've already
> seen", and keeping all elements that aren't in that set. I won't give
> you all the code, but here's the basic set operations:
>
> sighted = set()
> sighted.add(some_element)
> if some_element in sighted:   # condition is True if you've already
> seen this element

The itertools doc, in the last section, has a recipe for this problem 
that uses the above approach.


-- 
Terry Jan Reedy




More information about the Python-list mailing list