The remove_duplicates problems


#1

def remove_duplicates(x):
y=x
z=[]
for i in x:
y.remove(i)
if i not in y :
z.append(i)
return z
this is my code for the following problem , the error it shows is that i have modified the original list , i dont see how


#2

When we do this to make a copy of list.
Actually this means both of the list will point to one reference list.

If we make changes in one list then It will change both.
lets see one example...

x = [1,2,3,4,5]
y = x

print x
print y

Both of them will print [1, 2, 3, 4, 5]
Now lets say I removed one item from x..

x.remove(2)
print x

It will print [1, 3, 4, 5]

Now try to print y.

print y
You will surprised to know that It will print [1, 3, 4, 5]
Even you did not removed 2 from y list ,2 will be removed from it.As both of them point to same reference list.

To avoid this we write something like this to make copy of one list

y = x[:] (slicing)

One more thing..
You can write this program without even creating copy of list i.e y.


#3

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