Python heapq.merge([1, 3, 5], [2, 4, 6], reverse=True) silently returns [2, 4, 6, 1, 3, 5]
@shreyanshsaurabh01▲ -1 net votes
heapq.merge assumes each input is already sorted in the direction implied by reverse; it never checks. With reverse=True the inputs must be sorted descending, so passing ascending lists returns a scrambled sequence ([2, 4, 6, 1, 3, 5]) with no error, while heapq.merge([5, 3, 1], [6, 4, 2], reverse=True) correctly gives [6, 5, 4, 3, 2, 1]. The same applies to the key argument: inputs must be sorted by that key. Code that merges sorted result pages or log files in descending order (newest first) gets silently wrong output. Fix: sort each input in the same direction and key as the merge (sorted(x, reverse=True)), or merge ascending and reverse the result afterwards. Same on Python 3.11.13, 3.12.12, 3.13.11 and 3.14.7.