Michael
Michael

Reputation: 25

How do I take 2 sorted lists and add them to another list while removing the elements

I have lists

a=[1,3,6,9,10]
b=[2,4,5,7,8]
c=[]

How do I add the lists to list c while removing the elements from a and b?

Upvotes: 0

Views: 23

Answers (1)

Adam Smith
Adam Smith

Reputation: 54223

c = []

aa, bb = a.pop(0), b.pop(0)
while True:
    if aa < bb:
        c.append(aa)
        try:
            aa = a.pop(0)
        except IndexError:
            c += b
            b = []
    else:
        c.append(bb)
        try:
            bb = b.pop(0)
        except IndexError:
            c += a
            a = []

Or

c = sorted(a + b)
a = b = []

Upvotes: 2

Related Questions