Why doesn't this work?


#1



https://www.codecademy.com/en/courses/python-intermediate-en-rCQKw/2/4?curriculum_id=4f89dab3d788890003000096


"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:
            y.remove(i)
    return y


#2

Hello

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:
duplicates.append(x[i])
else:
if x[i] not in duplicates:
duplicates.append(x[i])
return duplicates
.
I did not indent it properly. But I think this should work.


#3

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


#4

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])


#5

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.


#6

Hey!

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:


#7

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


#8

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.


#9

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