Why doesn't this work?



"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!"

For example: remove_duplicates([1,1,2,2])
should return [1,2].

def remove_duplicates(x):
    duplicate = ""
    y = x
    for i in y:
        duplicate = i
        if i == duplicate:
    return y



I hope you do not mind I rewrote your code. I did not do my lesson this way, but combined what I did with yours.

def remove_duplicates(x):
duplicates = []
for i in range(len(x)):
if i == 0:
if x[i] not in duplicates:
return duplicates
I did not indent it properly. But I think this should work.


While I certainly appreciate your help, I'm not looking for the answer. My question is why doesn't the code work.


Some of the differences between the codes -

duplicate = "" had an error that a str object has no attribute to append. I changed that [].
I did not define y, I used the range in x.
I also used the append to fix it to that ranges - whether it is a duplicate or not.
I used an else function for non duplicates.
And return duplicates.

You can see if it works by adding this line at the bottom -
print remove_duplicates([1,20,1,1,3,20,0,0,4])


Perhaps the code required more lines of code, to execute the task.
Defining what is duplicates and what is not, etc.

I can not tell why your code does not work, but perhaps if you compare them it might answer your question.
Loops are tricky. Hope you get the answer you seek.



Your code modifies the list that it gets as a parameter and that's not good as it is forbidden in the instructions.

You should create second list which doesn't include duplicates and return that.

I hope that i could make myself clear enough :smiley:


But aren't I modifying list y, not x?


The name y points to the same list as the name x.

I think that this link can explain this better than I.
The link contains info about Python lists.


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