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


#1



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


#2

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.


#3

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

My code is as follows:
def remove_duplicates(seq):
new_seq = []
for i in range(0, len(seq)):
if new_seq == []:
new_seq.append(seq[i])
else:
for j in range(0, len(new_seq)):
if seq[i] == new_seq[j]:
new_seq = new_seq
else:
new_seq.append(seq[i])
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?


#4

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:
new.append(i)
return new


#5

Gotta give mad respect for the clean code.


#6

Thanks for the solution


#7

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