Problem with list.remove() method
rosuav at gmail.com
Tue Nov 20 15:14:38 CET 2012
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... 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
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:
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()
if some_element in sighted: # condition is True if you've already
seen this element
Hope that helps!
More information about the Python-list