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


#1

https://www.codecademy.com/courses/python-intermediate-en-rCQKw/2/4?curriculum_id=4f89dab3d788890003000096#

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:
            new_list.append(i)
    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]

#2

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


#3

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...


#4

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