Remove Duplicates -- loop failing


#1



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


Error: Oops, try again. remove_duplicates([4, 5, 5, 4]) returned [4] instead of [4, 5]


It seems like the loop isn't cycling through the entire list. Why?


def remove_duplicates(numbers):
    new_list = []
    for n in numbers:
        if numbers.count(n) > 1 and n not in new_list:
            new_list.append(n)
            return new_list
        else:
            return numbers


#2

The else can be removed. Be sure the return statement is outside of the loop.

return new_list

#3

Thanks mtf -- tried your advice but still running into an error

def remove_duplicates(numbers):
    new_list = []
    for n in numbers:
        if numbers.count(n) > 1 and n not in new_list:
            new_list.append(n)
    return new_list

Error: > Oops, try again. remove_duplicates([6, 8, 122, 2, 18]) returned [] instead of [8, 122, 18, 2, 6]

Thoughts? Thanks!


#4

That operation is not needed and may be interfering. It can be removed.

if n not in new_list:

#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.