My code works but I don't understand why. 15: REMOVE DUPLICATES


My function is correct according to codecademy but it returns every number in the list instead of only returning the duplicates. Can someone please explain why and show me how to only have the duplicates in my new list.
My code is posted below.

def remove_duplicates(lst):
    new_list = []
    for i in lst:
        if i not in new_list:
    return new_list
print remove_duplicates([1,1,2,3,3,4,4,5])
# prints [1,2,3,4,5] and not [1,3,4]


but the purpose of the exercise is to remove any duplicate values, and preserve single values.

What you are supposing is a bit more complicated. what you could do, is created another list:

more_list = []

and then add a else statement, to append any duplicate values to more_list, then before your return statement, remove any values from new_list which are not in more_list.

This will mean you can no longer pass the exercise


The numbers, 2 and 5 in your code, are not duplicates. And according to the code, they should be included in the new_list array.
The objective of this exercise is to return an array that does not contain duplicates, thus "remove_duplicates," without modifying the original array that was passed into it.
Unless your objective is to return an array with only the numbers that "are duplicates"... then see above... This will fail the exercise...


I see now, just misinterpreted the exercise, thanks a lot for clearing that up! :smile: