Remove duplicates edits original list


#1

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):
    copied_list=[]
    copied_list=original_list
    counter=0
    for x in copied_list:
        if x in copied_list:
            counter+=1
            if counter>2:
                copied_list.remove(x)
    print copied_list
    print original_list
    
remove_duplicates([2, 3, 4, 4, 5, 5, 5])

#2

You never made a copy of the list.

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


#3

okay, so how would i copy it?


#4

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


#5

thanks, man.
i get it now


#6

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


#7

no it doesn’t work :frowning:


#8

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


#9

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


#10

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:


#11

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