Remove_duplicates


#1

can anyone help me out , am getting an error in my code

a = [4,5,5,4]
def remove_duplicates(num):
    b = num
    l = []
    j = 1
    for i in b:
        if i not in b:
            continue
        else:
            l.append(i)
            b.remove(i)
    return l
print remove_duplicates(a)

Error is 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!
but am getting the exact output in the console


#2

The lesson checker expects the order to be preserved in the return value. The first 4 and the first 5 should be preserved, and the duplicates removed.

This is not a copy, but a shared reference. They are one in the same. To copy a list, use list slicing...

b = num[:]

This should be checking your working list, l.

if i not in l:

This is not necessary.


#3

Thank You now i traced my code and got the result ,I didn't read the last instruction so there was error

a = [4,5,5,4]
def remove_duplicates(num):
    b = num[:]
    l = []
    j = 1
    for i in b:
        if i not in l:
            l.append(i)
        else:
            continue  
    return l
print remove_duplicates(a)

#4

In point of fact we do not need to copy the original list since we are not modifying it.

for i in num:
   if i not in l:

From a coding perspective, l is a less than desirable choice for a variable name since it looks so much like a numeral 1. Recommend use something a little more explicit, such as result.

result = []

That line is not needed.


#6

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