14. remove_duplicates


#1
def remove_duplicates(lst):
    lst2 == []
    for i in lst:
        lst2.append(i)
    lst2 == lst
    return lst2

i got this error :Oops, try again. remove_duplicates([4, 5, 5, 4]) resulted in an error: global name 'lst2' is not defined


#2

this line:

lst2 == []

two equals sings means compare. to declare lst2 and give it an empty list as value, use a single equal sign


#3
def remove_duplicates(lst):
    lst2 = []
    for i in lst:
        lst2.append(i)
    lst2 == lst
    return lst2

Oops, try again. remove_duplicates([4, 5, 5, 4]) returned [4, 5, 5, 4] instead of [4, 5]

still does not work


#4

you just append all items from lst to lst2 without any check for duplicate values


#5

sorry, i dont really get you


#6

the purpose of this exercise is to remove duplicates from the list. so if you have the list:

[4,5,5,4]

your function remove_duplicates should return a new list with the values:

[4,5]

so you should only append items to the new list (lst2) if the number (stored in i, thanks to your for loop) if the number isn't in lst2 yet ( if i not in lst2)


#7
if i not in lst2:

this gives syntax error!


#8

can i see how you implanted it?

you do still need the for loop, i hope you gave it a good thought where to implant this


#9
def remove_duplicates(lst):
    lst2 = []
    for i not in lst2:
        lst2.append(i)
    lst2 == lst
    return lst2

#10

here it is
...........


#11

what i gave you was a if condition which you should have nested in the for loop, this way, each run of the loop, the if condition checks if the number is not yet in lst2


#12
def remove_duplicates(lst):
    lst2 = []
    for i in lst:
        if i not in lst2:
            lst2.append(i)
    lst2 == lst
    return lst2

@stetim94 :slight_smile:
thanks a lot i got it :slight_smile:


#13

do you also understand why this works?


#14

Yes, thanks a lot ...


#15