Practice Makes Perfect Remove_duplicates


#1



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:
            answer.append(number)
            other_lst.remove(number)
        else:
            answer.append(number)
    return answer


#2

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.

Good-luck.


#3

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:
        other_list.append(integer)

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.


#4

That makes sense, thank you!


#5

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


#6

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


#7

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?


#8

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


#9

Ah that makes sense, thanks :slight_smile:


#10

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