Problem with list.remove() method

Prasad, Ramit ramit.prasad at jpmorgan.com
Tue Nov 20 21:47:47 CET 2012


Alvaro Combo 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!!!
> 
> Any suggestion is MOST welcome.
> 
> Best Regards
> 
> ACombo
> 
> ...And the code:
> 
> def remove_dup_5_10():
>     """
>     Remove the duplicates of a given list. The original list MUST be kept.
>     """
> 
>     # Set the original list
>     lst = ['a', 1, 10.0, 2, 'd', 'b', 'b', 'b', 1, 2, 'b' ]
> 
>     # NEED to create a copy... See dicussion on Problem 5.6 and issue #2
>     cpy_lst = list(lst)
> 
>     # Perform an infinite loop... explained later
>     i=0 # initialize the index
>     while i != len(cpy_lst):
>         if cpy_lst.count(cpy_lst[i]) != 1:
>             cpy_lst.remove(i)
>         else:
>             i += 1
> 
>     print "The original List: ", lst
>     print "List with NO duplicates: ", cpy_lst
> 
>     return True
> --

Remove looks for the *value* not the *index* of the value.

>>> help([].remove)
Help on built-in function remove:

remove(...)
    L.remove(value) -- remove first occurrence of value.
    Raises ValueError if the value is not present.

Change ` cpy_lst.remove(i)` to `cpy_lst.remove(cpy_lst[i])`.

~Ramit



This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  


More information about the Python-list mailing list