Dev Helpers

Python / Data structures and algorithms

Merge sorted streams lazily

Dev Helpers · July 4, 2025

A lazy merge can yield the next smallest item across sorted inputs. Its ordering guarantee depends on each input already being sorted.

Worked example

from heapq import merge
print(list(merge([1, 4, 7], [2, 3, 9])))

Result

[1, 2, 3, 4, 7, 9]

Implementation notes

The source sequences must use the same comparison key. Merging by timestamp after sorting one feed by name can quietly produce an incorrectly ordered timeline.

Try it yourself

Compare two ordered feeds and deliberately scramble one feed.

Open the Python example →

Editorial date July 4, 2025 · Published December 6, 2026

Related articles

Run an async function

An async function call creates a coroutine. A top-level runner supplies the event loop that executes it.

Transpose a matrix

Transposing rows into columns assumes a decision about uneven rows. Ordinary zip stops at the shortest input.

Unpack with a remainder

Starred unpacking separates a fixed header from a variable-length tail. It still requires enough elements for the fixed positions.