A little confused on remove_duplicates


#1

curriculum_id=4f89dab3d788890003000096

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:
            results.append(i)
    return results

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


#2

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.


#3

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