14. remove duplicates- HELP PLZ


#1



def remove_duplicates(n):
    m = []
    m += n
    for i in m:
        for j in m:
            if i == j:
                m.remove(i)
                return m

I've been stuck for a while, please help. It only removes one duplicated


Replace this line with your code.


#2

oook so to do this problem, you should probably not add the old list to the new list like you did with
m += n
and instead try to add individual elements of n to m in the list so :

m = []  
for i in n:
    if i not in m:
        m.append(i)
return m

#4

@gingy2 is right, appending items to a new empty list is a easier way to solve this problem. There are a few problems with your code, both your for loops loop over the same list, which is a huge problem. since then the first item in the list always gets removed (they are the same), a function ends the moment a return keyword is reached, which happens the moment a number is the same, take a look at this code:

def remove_duplicates(n):
    m = []
    m += n
    for i in m:
        for j in m:
            print j,i
            if i == j:
                m.remove(i)
    return m
print remove_duplicates([4, 5, 5, 4])

i re-indented return, so all loops can run. But as you can see, 4 gets remove twice. This is not the way to go, use gingy2 solution instead


#5

@gingy2 's method is how I did it, but with different variables :slight_smile:

def remove_duplicates(x):
......a = []
............for b in x:
...................if b not in a:
...........................a.append(b)
......return a

Explanation:
Line 1: x is the list we're changing
Line 2: a is a new, empty list. this one will be made into the new x list
Line 3: for every item (b) in the list x...
Line 4: ... if that item is not already in list a...
Line 5: ... we add (append) that item to list a.
Line 6: returns a, the new list.


#6

@gingy2 's method is how I did it, but with different variables :slight_smile:

def remove_duplicates(x):
......a = []
............for b in x:
...................if b not in a:
...........................a.append(b)
......return a

Explanation:
Line 1: x is the list we're changing
Line 2: a is a new, empty list. this one will be made into the new x list
Line 3: for every item (b) in the list x...
Line 4: ... if that item is not already in list a...
Line 5: ... we add (append) that item to list a.
Line 6: returns a, the new list.

P.S. I already posted this, but I think it only sent to @gingy2 . So I posted it here.


#9

I know it may seem hard but I did it in 3 lines! Yes, 3 lines!
Code:

def remove_duplicates(numbers):
new_list = set(numbers)
return new_list

Apparently set does it all for you so sit back and relax