Practice Makes Perfect Remove_duplicates


Practice Makes Perfect, remove_duplicates

error message: 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!

I don't understand why I'm getting this error. I am not modifying the original list.

def remove_duplicates(lst):
    other_lst = lst
    answer = []
    for number in other_lst:
        if other_lst.count(number) > 1:
    return answer


I don't know why you're getting this error either, but the thing is you're returning "answer" at the end, which is a completely new list.

You could write this in one line. Try making the list into a set, and then back into a list.



I was seeing this issue myself. I resolved it by copying the list first.

So rather than.

other_lst = lst

I used

for integer in lst:

I think the issue with the former code is it creates a linker between the new list and the original list - so rather than defining a new list, you've just created an alias for the old list - thereby modifying the alias modifies the original list. I know that happens in C++ and C#, but wasn't sure it would happen in Python.


That makes sense, thank you!


You are correct. Simply typing other_lst = lst is just giving lst another alias.


Yay! I got it right :grinning: pretty happy about that :slight_smile:


Actually I have a question about Alias's.

using other_list = lst creates an alias, but using other_list = sorted(lst) does not? How come that doesn't just modify lst and create an alias for that?


sorted is a built-in function that returns a new list which you have assigned as other_list :slight_smile:


Ah that makes sense, thanks :slight_smile:


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