merge

class iteration_utilities.merge(*iterables, /, key=None, reverse=False)

Merge several sorted iterables into one.

Parameters:

iterables : iterable

Any amount of already sorted iterable objects.

key : callable or None, optional

If not given compare the item themselves otherwise compare the result of key(item), like the key parameter for sorted().

reverse : bool, optional

If True then merge in decreasing order instead of increasing order. Default is False.

Returns:

merged : generator

The merged iterables as generator.

See also

heapq.merge
Equivalent since Python 3.5 but in most cases slower! Earlier Python versions did not support the key or reverse argument.
sorted
sorted(itertools.chain(*iterables)) supports the same options and can be faster.

Examples

To merge multiple sorted iterables:

>>> from iteration_utilities import merge
>>> list(merge([1, 3, 5, 7, 9], [2, 4, 6, 8, 10]))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

It’s stable and allows a key function:

>>> seq1 = [(1, 3), (3, 3)]
>>> seq2 = [(-1, 3), (-3, 3)]
>>> list(merge(seq1, seq2, key=lambda x: abs(x[0])))
[(1, 3), (-1, 3), (3, 3), (-3, 3)]

Also possible to reverse (biggest to smallest order) the merge:

>>> list(merge([5,1,-8], [10, 2, 1, 0], reverse=True))
[10, 5, 2, 1, 1, 0, -8]

But also more than two iterables:

>>> list(merge([1, 10, 11], [2, 9], [3, 8], [4, 7], [5, 6], range(10)))
[0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 11]

However if the iterabes are not sorted the result will be unsorted (partially sorted):

>>> list(merge(range(10), [6,1,3,2,6,1,6]))
[0, 1, 2, 3, 4, 5, 6, 6, 1, 3, 2, 6, 1, 6, 7, 8, 9]
__length_hint__()

Tries to estimate for the length of the instance (returns 0 if an estimation is not possible).

Note

Requires Python >= 3.4

key

(callable or None) The key function used by merge (readonly).

New in version 0.6.

reverse

(bool) Indicates if merged by > instead of < (readonly).

New in version 0.6.