Remove duplicate


#1



def remove_duplicates(lits):
    new_list = []
    for x in lits:
        if new_list==[]:
              new_list.append(x)
              continue
        for y in new_list:
            if x!=y:
               new_list.append(x)
        
            
                
    return new_list

what is wrong with my code plz help


Replace this line with your code.


#2

this condition:

if x!=y:

won't work, its not only about succesive items which are the same.

if we have:

[1,2,3,1]

the result should be:

[1,2,3]

your code won't do this because the 1's are not next to each other, so your if condition never catches it

Maybe you should check the hint in the lesson?


#3

for y in new_list:
if x!=y:
new_list.append(x)
"""this part will iterate through the new list before appending in the new list so i think there is no chance of repetition of the numbers...."""


#4

i see where you are going. But that is not what is currently happening

What you want to do is use this loop to check if x is in new_list, if not, append to new_list, right?

currently, for each value (y) in new_list which doesn't equal x, we append x to new_list


#5

def remove_duplicates(lits):
    c=0
    new_list = []
    for x in lits:
        if new_list==[]:
              new_list.append(x)
              continue
        for y in new_list:
            if x!=y:
               continue
            else:
                 c+=1
                 
        if c==0:     
            new_list.append(x)
        
            
                
    return new_list

"""please help me correcting this code"""


#6

here:

c=0

could you explain why you placed c=0 where you did?

it means that once a duplicate value is found in new_list, c will never be zero again, so all values after the first duplicate value won't be added


#7

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