Remove_duplicates question


Its working

why does the if statement assume that the list new has inputs if i didn't append anything to it

def remove_duplicates(x):
    new = []
    for i in x:
        if i not in new:
    return new


It doesn't assume that the list has anything at all in it. In a series of iterations, it checks whether each i is not yet in the list. If a given i is not yet there, then it appends that i to the list.

The list starts out empty. Provided that x is not empty, the first item in x is not yet in the new list, and it gets appended to it. In turn, each i in x gets checked, and appended, if necessary.


def remove_duplicates(lst):
new_lst = lst

j = 0
while j < len(lst):
    k = j+1
    while k < len(lst):
        if lst[j] == lst[k]:
        k = k + 1
    j = j+1

return new_lst

print remove_duplicates([1,1,2,2])

Though I've made a copy of original list (lst) in a new list (new_lst) and modifying the new one, the original list is getting modified as well. Why is it so?


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