Batu Lab NotesPractical developer guides

Merge two sorted number streams deterministically

By Batu ยท English technical notes

Also published in our Blogger archive.

When two inputs are already sorted in ascending order, heapq.merge produces one ascending iterator from them. Here the left stream is [1, 4, 7] and the right stream is [1, 3, 8]; materializing the iterator yields [1, 1, 3, 4, 7, 8]. The duplicate 1 is retained, because merging combines values rather than removing repeats.

heapq.merge is useful when inputs can be iterated in order and a complete combined list is not always needed. In this compact example, list() is used only so the result can be asserted and printed. The function accepts multiple sorted iterables, and its key and reverse options support matching ordered inputs. Basic heapq.merge is part of Python's standard library; the key and reverse parameters require Python 3.5 or later.

Determinism depends on the stated precondition: both source streams must already be sorted with the same ordering rule. Passing unsorted inputs does not make merge sort them and can yield an incorrectly ordered result. Likewise, numbers such as float('nan') do not have ordinary total-order behavior and are a poor fit for this simple contract. The assertion verifies this known fixture, not arbitrary upstream stream quality.

AI assistance disclosure: this article was drafted with AI assistance and checked against the cited Python documentation.

from heapq import merge

left = [1, 4, 7]
right = [1, 3, 8]

merged = list(merge(left, right))

assert merged == [1, 1, 3, 4, 7, 8]
print(merged)
[1, 1, 3, 4, 7, 8]