'remove_duplicates' Iterative solution without using 'Not in'


#1

After briefly forgetting that the built in 'Not in' operation exists I inadvertently solved this problem using only a 'For' and 'While' loop (in addition to a well placed 'break' statement). I've posted it here in case anyone might find this type of answer useful.

def remove_duplicates(lst):
    new_lst = []
    x = -1
    for item in lst:
        x += 1
        y = x
        while y < len(lst) - 1:
            y += 1
            if lst[x] == lst[y]:
                break
        else:
            new_lst.append(lst[x])
    return new_lst

Essentially the function starts with the first item in the list and compares it with the items that come after it. However, it stops comparing and starts again with the next item in the list if it finds a repeat of the item being compared. It only appends an item to the new list if it completes all comparisons without breaking.


#2

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