Original Being modified in remove_duplicates


#1

Original List is being modified by my created function:
Exercise Link : [remove_duplicates]
Error Code:
"
Oops, try again. Your remove_duplicates modifies the list that was passed to it. [4, 5, 5, 4] was modified to [4, 5]. Perhaps you should make a copy first!
"
Expectation : The Original List should remain as such. And the code clearly returns the duplicated list

Please help. Below is the code:


def remove_duplicates(lst):
    l=lst
    print l, lst
    ln=len(l)
    print ln
    j=0
    for i in range(0,ln):
        j=i+1
        while j<ln:
            print i,j ,l[i],l[j]
            if l[i]==l[j]:
                l.pop(j)
            print l
            ln=len(l)
            j=j+1
            print ln
    print lst, l
    return l
    
print remove_duplicates([4,5,5,4])

However, the below code works just fine:


def remove_duplicates(lst):
    l=[]
    print l, lst
    ln=len(lst)
    for i in range(0,ln):
        print lst[i]
        if lst[i] not in l:
            l.append(lst[i])
    return l
    
print remove_duplicates([4,5,5,4])


#2

this line:

l=lst

won't make a copy of a list, l now refers to lst. to make a copy:

l=list(lst)

also, the exercise test with lists like [6,6,6,6,6], not sure your code can handle it


#3

Thanks, it helps.

Also, regarding [6,6,6,6,6] test case, it is failing and I found the reason.