Remove_duplicates


#1



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


It is coming up with this error message:

Oops, try again. Your remove_duplicates modifies the list that was passed to it. [4, 5, 5, 4] was modified to [5, 4]. Perhaps you should make a copy first!


def remove_duplicates(lst):
    x = lst
    lst = lst
    result = []
    bin = []
    for num in lst:
        y = [x.remove(num)]
        if num not in x:
            result.append(num)
        else:
            bin.append(num)
    return result


Any help would be greatly appreciated.


#2

The exercise expects the result to maintain the orginal order.

This is overwriting a built in function. Not a good idea to use reserved words as variable names. Not the issue, here, per se, but something that could be an issue if your code expected to use the function.

This is causing your values to be appended in reverse order of the original list.

Also, you do not need a secondary list (bin) or an else branch. Just build your new list from the allowed values.


#3

Thanks.
I tried this, and it still comes up with the same error.

def remove_duplicates(lst):
result = []
x = lst
for num in lst:
y = x.remove(num)
if num not in x:
result.append(num)
y = x.append(num)
return result

I don't really understand what you are saying I need to do. It also says in the excercise that it doesn't matter what order you return it.

I thought that the error was saying, that the issue is that I am modifying the original list. But, I don't think I am? I made a copy'x' and use that.


#4

This has always made me shake my head. The SCT does not agree with the instructions or we would not be getting that messsage.

y will be None

>>> n = [1,2,3]
>>> print (n.append(4))
None
>>> print (n)
[1, 2, 3, 4]
>>> y = n.remove(4)
>>> y
>>> print (y)
None
>>> n
[1, 2, 3]
>>>

Like append, remove does not have a return.

def remove_duplicates(lst):
    result = []
    # x = lst    
    for num in lst:
        # y = x.remove(num)
        if num not in x:
            result.append(num)
        # y = x.append(num)
    return result

I've commented out all the lines that cause issues.

Contrary to we might intuitively believe, x is not a copy of lst. It IS lst under a new name (reference).

To copy a list use,

x = lst.copy()

or,

x = lst[:]

#5

Thank you so much, changed it to:

x = lst[:]

Everything else seemed to be fine.

By the way, it said ".copy()" doesn't work for lists.


#6

Got you to try it, though. Good on you. Thanks.

https://www.programiz.com/python-programming/methods/list/copy


#7

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