A little confused on remove_duplicates



When I run the code it gives me

Oops, try again.
remove_duplicates([4, 5, 5, 4]) resulted in an error: list assignment index out of range

and yet in the console window it shows the list being returned correctly. I was expecting i could simplify the process by first checking my own list to see if the number had already been added and if so remove the number. The console shows that I was correct but the error says otherwise.

Would someone mind explaining to me what I'm doing wrong? Did I use the wrong syntax?

def remove_duplicates(items):
    results = []
    for i in items:
        if i in results:
            del items[i]
        elif i not in results:
    return results

print remove_duplicates([1,1,2,2,3,3,4,4,5,5])


lets say if a list has 6 items, and you remove two (del items[i]), your list has now 4 items, but the for loop you have:

for i in items:

still needs to think it needs to loop over 6 items, but those items aren't there anymore. Causing an index error

Why not simply only append numbers which aren't in the results list yet, into the results list? Remove the del altogether.


That makes so much sense, thank you so much! I was overthinking it which I do a lot, but thanks for the help!:grin: