PythonMastery
Python programs · Functions · beginner

Merge two sorted lists in Python

Combine two sorted lists into one sorted list by walking through both with two positions, then the shorter ways with heapq.merge() and sorted().

Both lists are already sorted, so the smallest remaining item is always at the front of one of them. Compare the two front items, take the smaller one, and move forward in that list. Repeat until one list is used up.

The program

python
def merge_sorted(a, b):
    result = []
    i = j = 0
    while i < len(a) and j < len(b):
        if a[i] <= b[j]:
            result.append(a[i])
            i += 1
        else:
            result.append(b[j])
            j += 1
    result.extend(a[i:])               # at most one of these two adds anything
    result.extend(b[j:])
    return result

print(merge_sorted([1, 4, 9, 12], [2, 3, 10]))
print(merge_sorted([5, 8], []))
print(merge_sorted([2, 2, 7], [2, 5]))
output
[1, 2, 3, 4, 9, 10, 12]
[5, 8]
[2, 2, 2, 5, 7]

How it works

This merge is the second half of merge sort.

Another way: heapq.merge() and sorted()

python
import heapq

a = [1, 4, 9, 12]
b = [2, 3, 10]
c = [0, 11]

print(list(heapq.merge(a, b)))
print(list(heapq.merge(a, b, c)))
print(sorted(a + b))
output
[1, 2, 3, 4, 9, 10, 12]
[0, 1, 2, 3, 4, 9, 10, 11, 12]
[1, 2, 3, 4, 9, 10, 12]

Learn the idea: Loops: for, while, and the Pythonic Patterns, Lists & Sequences