Remove duplicates edits original list


With the code i wrote it also edits the original list while you’re not supposed to.
how does this happen i dont understand, i only copy it right?

def remove_duplicates(original_list):
    for x in copied_list:
        if x in copied_list:
            if counter>2:
    print copied_list
    print original_list
remove_duplicates([2, 3, 4, 4, 5, 5, 5])


You never made a copy of the list.

you have two variable which point to the same list in memory


okay, so how would i copy it?


you could do it manually, use a loop and .append() but there is also a built-in function


thanks, man.
i get it now


Its a complicated solution you choice, does it even work?


no it doesn’t work :frowning:


removing from the list you are looping over is a bad idea.

furthermore, even if you get it to “work”, the following list:

[1, 2, 3, 3, 2, 1]

would produce:

[3, 2, 1]

while it should be produce:

[1, 2, 3]

the exercise would still let you pass, but its not good enough.

Someone also made a topic today with exactly the same question, same advise here: avoiding .remove() would be the wise decision, you have seen how difficult it is


okay, apparently the order doesn’t matter. (i misread it)

still, thepitycoder and i puzzled with it, we came up with two very different solutions, and both deemed them unnecessary complicated.

so going for the .remove() approach is absolutely not recommended


Yeah, that was a fun puzzle.

Seriously, trying to get this to work using .remove() is definitely a satisfying challenge if you want to push yourself and see if you can do it, but there’s much easier and more efficient ways of doing it which is what the lessons try and get you to realise.

Coding something badly, by making it more complex than necessary just because you can or to show off, is bad form. :slight_smile:


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