Ordered list union

Published: Wednesday, Dec 26, 2007 Last modified: Thursday, Nov 14, 2024

list1 = [1,2,3,4,5,6]
list2 = [1,2,3,3,5,6]
list3 = [5,6,7]
list4 = ['cow', 'rabbit']
list5 = ['rabbit', 'mushroom']
list6 = ['mushroom', 'rabbit']
list7 = None

def union(seq1,seq2):
    """ Get rid of duplicates in a list, and keeps *order* """
    d = []
    if not seq1:
        return seq2
    if not seq2:
        return seq1
    for x in seq1:
        if x not in d:
            d.append(x)
    for x in seq2:
        if x not in d:
            d.append(x)

    return d

if __name__ == '__main__':
    print union(list1, list2)
    print union(list1, list3)
    print union(list4, list5)
    print union(list4, list6)
    print union(list7, list6)
    print union(list6, list7)


[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6, 7]
['cow', 'rabbit', 'mushroom']
['cow', 'rabbit', 'mushroom']
['mushroom', 'rabbit']
['mushroom', 'rabbit']