remove_duplicates: why my function doesn't make a copy?


def remove_duplicates(x):
    hola = x
    for i in range(len(hola)):
        n = len(hola)-1
        while n > i:
            if hola[i] == hola[n]:
                del hola[i]
            n -= 1
    return hola
print remove_duplicates([1,2,2])

Hello! I thought that line hola = x will assure that x won''t change and any changes will be implemented only in hola list. But it looks like I was wrong. Can you explain me why and make my code better (beacuse it actually removes duplicates - the problem is "Perhaps you should make a copy first!")?


The problem is indeed that hola = x doesn't set to hola a copy of x.
To understand this, you should stop seeing x as being equal to [1,2,2] but as a label to the list [1,2,2]. If you do hola = x, you're actually just attaching a new label to [1,2,2]: the 'hola' label.

Now how would you fix this? There are several ways, of which I think the clearest one is:
hola = list(x). This works because list is a constructor and will always create a new list. This way you're not referencing to the same list, but to a copy.


My code is as follows:
def remove_duplicates(seq):
new_seq = []
for i in range(0, len(seq)):
if new_seq == []:
for j in range(0, len(new_seq)):
if seq[i] == new_seq[j]:
new_seq = new_seq
return new_seq

print remove_duplicates([1,1,2,2])

I am getting the following error: Oops, try again. remove_duplicates([4, 5, 5, 4]) returned [4, 5, 5, 4] instead of [4, 5]

Could you help?


you guys are making this way to complicated.
here is my code
def remove_duplicates(x):
new = []
for i in x:
if i not in new:
return new


Gotta give mad respect for the clean code.


Thanks for the solution


def remove_duplicates(items):
new_list = set(items)
return new_list