Remove_duplicates


#1


Hi everybody!
This is a question from Practice makes perfect, 14th question-->(remove_duplicates)

I tried to debug it many times but code isn't working? Can somebody help me out?


def remove_duplicates(l1):
    l2=l1
    for i in range(len(l1)):
        if i==len(l2)-1:
            break
        for k in range(i+1,len(l2)):
            if l2[k]==l2[i]:
                l2.remove(l2[k])
        
    return l2


#2

you don't necessarily need this line as the for loop will terminate when the range specified.
In any case try not to remove from a list you are actively iterating instead you can create an empty list and copy over only unique values from the previous list and return the new list


#3

def remove_duplicates(rr):
e = list(set(rr))
return e


#4

I think you're over complicating things here.
The hint pretty much tells you the answer:

if '''var for numbers in original list''' not in '''name of new empty list''':

You can use this code to check for duplicates and add the numbers in if they're not already added.
Hope this helps!


#5

Hi this code works.
What do you guys think about it?

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

#6

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