Problem with list.remove() method

Alvaro Combo alvaro.combo at gmail.com
Tue Nov 20 14:56:27 CET 2012


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


More information about the Python-list mailing list