Remove_duplicates


#1

Can someone help me understand why I'm throwing this error?

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

Per my code the first thing I did is make a copy of the list and the only modification was to the new list.


lst = [4,5,5,4]

def remove_duplicates(n):
    lst2 = n # copies input into new list 
    for i in lst2: # loop through list
        if lst2.count(i) > 1: # check if duplicated
            lst2.remove(i) # if dup, remove from list
        
    return lst2

print remove_duplicates(lst)


#2

When you do:

lst2 = n

You are not making a copy. You are creating another name for the same list. Python doesn't create new variables when you do this, just a new name for it. So, whatever you do with lst2 will affect n as well. There are other methods to copy such as:

lst2 = n[:]

or

lst2 = list(n)

#3

thanks
this helped a lot


#4

No problem! I'm happy that it was helpful :slight_smile:


#5
def remove_duplicates(original_list):
    new_list = []
    for item in original_list:
        if item not in new_list:
            new_list.append(item)
    return new_list

#6

def remove_duplicates(x):

ls2= []

lool = dict(zip(x,x))

for dd2, value in lool.items():        
    ls2.append(value)
return ls2

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


#7

Simplest way to do this from what i've found is using the "set" function within the "list" function..

def remove_duplicates(dupes):
    return list(set(dupes))
    
print remove_duplicates([1,1,2,2])

Hope this helps, definitely cut my code down by double, or even triple.