Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

heapq.merge

Lazily merges pre-sorted streams into one ordered stream.

Version: Python 3.14; repository image, production runtime not attested

Syntax

heapq.merge(*iterables, key=None, reverse=False)

Lazily merges pre-sorted streams into one ordered stream.

Each input must already follow the chosen ordering. Equal items from different inputs remain in the result.

Use merge to stream records from multiple sorted inputs. It returns an iterator and obtains elements as needed. The key function defines the required ordering of each input. With reverse=True every source must already be descending. In the example an empty input contributes nothing and the two occurrences of 1 both survive.

from heapq import merge
seen = []
def source():
    seen.append("read")
    yield 4
stream = merge(source(), [3], reverse=True)
assert seen == [] and list(stream) == [4, 3]
assert list(merge(["aa", "z"], ["bbb"], key=len, reverse=True)) == ["bbb", "aa", "z"]

Examples

import heapq
print(list(heapq.merge([1, 4], [], [1, 3, 8])))

Result

[1, 1, 3, 4, 8]

Use merge to stream records from multiple sorted inputs. It returns an iterator and obtains elements as needed. The key function defines the required ordering of each input. With reverse=True every source must already be descending. In the example an empty input contributes nothing and the two occurrences of 1 both survive.

Sources